Filter by tags in Kirby

Filter by tags in Kirby

Since a few days I have made it possible to filter my blogposts by tags. I found it very easy to implement tags in Kirby. In this blogposts I will show you how.

1. Add a tags field

We start with adding a tags field to our article yaml blueprint:

tags:
  label: Tags
  type: tags

You can add lower: true to make sure that every tag is automatically converted to lower case. Tags are by default separated with a ,. You can change the separator with separator: /.

We now have a tags field:

2. Filter by tags

This is how our blog controller looks like:

<?php

return function($site, $pages, $page) {

    // fetch all visible pages
    $articles = $page->children()
                     ->visible()
                     ->flip();

    // filter by tags if filter applied
    if($tag = param('tag')) {
        $articles = $articles->filterBy('tags', $tag, ',');
    }

    // fetch all tags
    $tags = $articles->pluck('tags', ',', false);

    // apply pagination
    $perpage  = $page->perpage()->int();
    $articles = $articles->paginate(($perpage >= 1)? $perpage : 5);

    return [
        'articles'   => $articles,
        'pagination' => $articles->pagination(),
        'tags'       => $tags,
        'tag'        => $tag
    ];
};

3. Show tags of blogposts

We can show all tags of an article:

<?php foreach(str::split($article->tags()) as $tag): ?>
    <a href="<?php echo url('/' . url::paramsToString(['tag' => $tag])) ?>">
        #<?php echo html($tag) ?>
    </a>
<?php endforeach ?>

4. Show all tags

We can also show all tags. First we fetch all tags:

<?php
    $tags = $page->children()->visible()->pluck('tags', ',', true);
?>

and then show all tags:

<?php foreach($tags as $tag): ?>
    <a href="<?php echo url('/' . url::paramsToString(['tag' => $tag])) ?>">
        #<?php echo html($tag) ?>
    </a>
<?php endforeach ?>

Tip: check if filter by tag is applied

In a view, we can check if a filter by tag is applied with:

<?php
    if(param($key = 'tag', $default = null) == null):
?>

This will return true if a filter by tag is applied.

You can filter my blogposts by tags, for example: #java.


SHARE THIS ARTICLE