Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a series of posts that all reside within a 'Main' parent category. Various posts are assigned to sub-categories.

What I need to do is display the direct parent category for the currently viewed post, without showing other categories. Here is what I have:

  • MainCat

    • subcat1

      • post a
      • post b
    • subcat2

      • post c
      • post d
      • post e
    • subcat3

      • post f
      • post g

When viewing, for example, post 'a', I need to display subcat1 - not MainCat.

I want to echo this in a custom template for this post type, and need to display the posts subcategory as a link.

I've searched all over, and have found numerous snippets that show categories, subcats, etc.. but none that will only show a posts subcat like this.

share|improve this question

1 Answer 1

Check if each category has a parent:

foreach( ( get_the_category() ) as $category ) { 
    if( $category->category_parent != 0 ):
        echo $category->cat_name . ' is a child category ';
    else:
        echo $category->cat_name . ' is a parent category ';
    endif;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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