0

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.

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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