Group pages by tags

So I want to group a list of events by tags feild. Some of them have multiple tags. I want to create headings on the page with each tag in an H2 and then articles that have that tag listed underneath.

This is close… Sort by a tag from a tags field

But its for kirby 2 not 3 and i dont know the tag name up front, i just want to group articles together by tag under a heading for each tag. It doesnt matter if an article gets listed twice in two seperate groups if it has more than one tag.

How would i do that?

The simple approach:

  • get all tags using $page->children()->pluck('tags', ',', true). This gives you an array of all tags
  • loop through this array of tags and filter your page by each tag.
$children = $page->children()->listed();
$tags = $children->pluck('tags', ',', true);

foreach ($tags as $tag): ?>

<h2><?= $tag ?></h2>
    <?php foreach ($children->filterBy('tags', $tag, ',') as $child): ?>
        <h3><?= $child->title()->html() ?></h3>
    <?php endforeach ?>
<?php endforeach ?>

Improve markup with list and only if collection for tag exists etc.

1 Like

Oh of course… its basiclly a fancy tag list… my old brain was over complicating… @texnixe your a marvel, thanks :slight_smile:

Yes, with my super old brain :joy:

pfff… .works better then mine :slight_smile:

Is there an easy way to add on how many items there are for each tag after the tag name?

I think the best way would be to pluck the tags with the unique parameter set to false and then count how many times each tag is contained in the resulting array. The alternative would be to filter the collection by each tag and then count the result, but performance-wise that is not really recommendable.

1 Like