Get the current category slug in Wordpress / Timber

user818700 picture user818700 · Jun 27, 2016 · Viewed 16k times · Source

In my Single.php I'm trying to get the current posts category slug:

$category = get_category(get_query_var('cat'));
$cat_slug = $category->slug;

But it doesn't return anything. And there's definitely a category on the post. What am I doing wrong?

Answer

Gchtr picture Gchtr · Jun 27, 2016

You can go with get_the_category(), but since you tagged your question with Twig and Timber, I thought maybe you want to do it «the Timber way».

With Timber you can access a lot of functionality via methods on the objects. For the TimberPost class, there’s a method terms(), which will get you all terms for a post. Pass the name of the taxonomy you want to get terms for. In your case: category.

single.php

<?php

$context = Timber::get_context();
$post = Timber::get_post();

$context['post'] = $post;

// Get all categories assigned to post
$categories = $post->terms( 'category' );

// Get only the first category from the array
$context['category'] = reset( $categories );

Timber::render( 'single.twig', $context );

In versions below Timber 1.x there were also methods like category() and categories() to get either one or all terms of the category taxonomy, but they seem to be deprecated now.

single.twig

In your Twig file, you then can easily access the slug through

{{ category.slug }}

You can also directly call the terms() method from Twig and pass the result to a for loop. This will echo out all categories assigned to the post.

{% for category in post.terms('category') %}
    {{ category.slug }}
{% endfor %}