Tag count in tag cloud

I want to list the top 15 tags from blog posts but the code below does not work. H ow do I fix this?



	// fetch all tags
	$tags = $page->children()->listed()->pluck('tags', ',', true);
	<ul class="tags">
	  <?php foreach ($tagCount as $tag => $count) {
	  if ($i >= 15) break;  ?>
		<a href="<?= url('blog', ['params' => ['tag' => $tag]]) ?>">
		  <?= html($tag) ?>
	  <?php endforeach ?>

What does that mean?

$tags in your code above return all tags as a simple array ['tag1', 'tag2', 'tag3'], and you are getting only the unique ones, because you set the third parameter to true in the pluck method.

Do you only want to get the first 15?
Do you want to get the most used 15 tags?

So if you want to get a count on how many times a value is used:

  1. Don’t use the true parameter

    $tags = $page->children()->listed()->pluck('tags', ',');
  2. Then apply `array_count_values()

    $tags = array_count_values($tags);

This will return something like

    [blue] => 1
    [green] => 2
    [red] => 1
    [orange] => 1

  1. then sort the stuff

  2. Get the first 15

    $tags = array_slice($tags, 0, 15);