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?
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
.
<?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.
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 %}