Listing non-empty categories in Timber

Category: Development | March 2017.

These days, I use Timber for all things WordPress. And it’s amazing.

However, if you are used to doing things the old fashioned way (i.e. with PHP templates), even accomplishing the simplest of tasks using Timber is not always obvious, despite all the brilliant documentation. So any useful little discoveries I make, I will document in this Journal.

My first noteworthy post is about listing categories that appear in a blog. Often, when we list categories, we only want to list those that have an attached post, banishing empty categories from our lovely menu.

So, in your php file (e.g. index.php), find this:

$context['categories'] = Timber::get_terms('category');
$context['categories'] = $categories;

And replace it with this:

$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => '1'
) );

$context[‘categories’] = $categories;

and add this to your twig file (e.g. index.twig), where you want the category menu to appear:

{% for cat in categories %}
<li {% if term.slug == cat.slug %}class="active"{% endif %}><a href="{{blog.link}}category/{{cat.slug}}">{{cat.name}}</a></li>
{% endfor %}

Easy 🙂