user818700
user818700

Reputation:

Get the current category slug in Wordpress / Timber

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?

Upvotes: 2

Views: 21624

Answers (3)

Usama Munir
Usama Munir

Reputation: 635

You can use:

$context[ 'category' ] = Timber::get_term(['taxonomy'=>'category']);

and in your twig file:

{{ category.title }}

Upvotes: 0

Gchtr
Gchtr

Reputation: 2804

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

Upvotes: 4

pallavi
pallavi

Reputation: 359

You can try this code to solve your issue:

foreach (get_the_category() as $category) {
    echo $category->slug .' ';
} 

Upvotes: 1

Related Questions