I have a custom post type called recipes.In this I have lots of recipes as posts.All these recipes are assigned to several categories.

Problem : Now Consider a post which is assigned to multiple categories. On single.php of that post, if i try to retrieve the category of post then I am getting the category which is alphabetically first every time.

I have tried retrieving category from url but it is possible only if I go to recipe template THROUGH the category template...

How to tackle this if we have a post assigned to multiple categories...Please help

1 Answer 1


If a post has multiple categories there is no "correct" category. Any of them are correct, it's a many-to-one relationship.

Since a post can belong to multiple categories it's a mistake for any function to assume a single category. Expect an array.

If you're looking to apply conditions based on one or more categories you could try if(has_category($category)) (if you're not in the Loop you'll need to pass the post object as the second parameter).

Edit from comment:

if(has_category('fitness')) { 
    // Example custom field 
    echo get_post_meta($post->ID, 'fibre', true);
if has_category('children') {
    // Example custom field  
    echo get_post_meta($post->ID, 'protein', true);
  • Actually i have to apply conditions based on category name...if a post belongs to category 'A' then i will print something on single.php of THAT post...else if it belongs to category 'B' then i will print something else on single.php of THAT post...and so on...Is this possible for a post with multiple categories? If i cant retrieve that category then i cant apply conditions based on it.
    – Kola
    Jul 18, 2017 at 11:11
  • I've updated my answer.
    – Chris Cox
    Jul 18, 2017 at 11:15
  • ok so has_category doesn't really serve my purpose as it will tell me if a post has that category or not....I cant use that much information to apply category specific conditions....Your initial answer pretty much explained the whole scenario...thanks a lot
    – Kola
    Jul 18, 2017 at 12:19
  • You can easily use that - if( has_category( $cat ) ) { /* $cat-specific stuff here */ }`
    – Chris Cox
    Jul 18, 2017 at 12:27
  • I am sorry...I am not getting the logic....If a post is in category A and category B, then... if (has_category('category A')) { category specific code for 'A' }... else if (has_category('category 'B')) { category specific code for 'B' }... this is fine but I cant really avoid clash of two categories....Because both conditions ARE NOT mutually exclusive..they both are true at the same time..
    – Kola
    Jul 18, 2017 at 12:48

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.