My post category structure is 3-level deep:

  • Products

    • Milk products

      • Milk

      • Chocolate

      • Cheese

I want to show all posts from "Milk products" and add appropriate category slug as class, for example - a post with name "Cacao Chocolate" is inside Chocolate category and I want it to have "Chocolate" slug.

With the following code all my posts added to category "Milk products" have the slug "Milk" - doesn't matter if they are also in category Milk, chocolate or cheese.


while ( have_posts() ) : the_post();
    echo '<li class="mix '. $category->slug .'" data-filter="'. $category->slug .'">'. get_the_content() .'</li>';


// Reset Query

Any idea how to get the the last category slug of the post?

1 Answer 1


First, Please don't use query_posts..

Second, you've set $category somewhere in code not posted and never change it. How do you expect it to be different? What you need to do is retrieve the categories, which isn't that hard...

$cq = new WP_Query('category__in=4');
while ( $cq->have_posts() ) {
  $c = wp_get_object_terms($post->ID,'category');
//   echo '<li class="mix '. $category->slug .'" data-filter="'. $category->slug .'">'. get_the_content() .'</li>';

... but categories don't really have an "order" unless you've made an effort to give them one, so I don't know how you are going to get the "last" category or even really what that means.

There is a similar issue with your statement that it "doesn't matter if they are also in category Milk, chocolate or cheese". There is nothing by default to mark the "primary" category so if there are multiple categories I am not really sure how to pick the one "correct" one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.