Get Top Parent Category (WordPress)

Get Top Parent Category (WordPress)

There are many times when you need to show or get the top most (root) parent category in WordPress – regardless of how many subcategories you might be deep. I have used this logic for page navigation (highlight the top parent tab) – as well as within some custom loops/sidebar code.

They way to do this:

// get parent category slug
$parentCatList = get_category_parents($cat,false,',');
$parentCatListArray = split(",",$parentCatList);
$topParentName = $parentCatListArray[0];
$sdacReplace = array(" " => "-", "(" => "", ")" => "");
$topParent = strtolower(strtr($topParentName,$sdacReplace));	

To test this you can simply put it in your header and echo out $topParent and you will see the “slug” of the category.
If you want to see the category name and not necessarily the slug – you can simply echo $topParentName.

45 thoughts on “Get Top Parent Category (WordPress)”
  1. Chris M |

    It just echos out “Object”..

    • Ngqabutho |

      @ those interested

      post;
      $category = get_the_category();
      $parent = get_cat_name($category[0]->category_parent);
      if ($parent == “Interviews” ) {
      include(TEMPLATEPATH . ‘/single_interview.php’);
      } else {
      include(TEMPLATEPATH . ‘/single_blog.php’);
      }

      ?>

      this sees if the parent is “Interviews” and opens “single_interview.php”

      this is the whole code for the “single.php”… coz the redirect is the normal single post template which it “single_blog.php”

  2. jzelazny |

    Put a if (is_category()) {} around the code and then echo it out. Check out the full example: http://jzelazny.wpengine.com/downloads/wordpress-logic/top-category.phps

  3. f1shman |

    thanks alot!!
    i was searching for a long time to find such a solution πŸ˜‰

  4. f1sHMaN |

    hmm, why isn’t it working on the front page?
    what can I change that it will output the cat. name on the frontpage?
    I want to add the top parent category name as a class!

    thx
    greets froms switzerland

  5. jzelazny |

    Hello f1sHMaN from Chicago! Do you have this logic within (is_category()){}? Make sure you check out the comment above yours where you can see the logic in action.

  6. f1sHMaN |

    that is the problem! what can i change to have the name of the topcategory (topParentName) on the frontpage?

    your script only goes on the category page.
    On the frontpage it returns: object…
    thx alot!

    • Mr. Manoj |

      What u want this code is only applicable for single template and category template.

    • Ngqabutho |

      post;
      $category = get_the_category();
      $parent = get_cat_name($category[0]->category_parent);
      if ($parent == “Interviews” ) {
      include(TEMPLATEPATH . ‘/single_interview.php’);
      } else {
      include(TEMPLATEPATH . ‘/single_blog.php’);
      }

      ?>

  7. Sarah |

    This is great! Thank you so much!!!

  8. Sarah |

    I have a question:
    How can I make this work for the single view of a post.

    Say I have a category Gallery and a category Work.
    With your code I have body class = category_gallery for the Gallery and body class = category_work for the work category. Great!

    Now I’d like to have body class = single_gallery when on the single view for any post in the Gallery category and body class = single_work when on a single post in the work category.

    I hope that’s not too confusing.
    How would this be done?

  9. Katherine |

    Any way to make it a live link?? I’m sure there IS a way… I’m just not that savvy when it comes to wordpress codex. Any help would be appreciated!!

  10. Rosario |

    Wow.. Thanks for the list πŸ™‚

  11. discostrings |

    Thanks! You just saved me some time and frustration in hacking this out myself.

  12. Alen |

    Big thanks ! Your code resolved my need to display banners by category groups (aka parents).
    Thank you again !

  13. mark |

    Thanks for this.Im going to give it a try.

  14. Reino |

    This works for me! Thanks!

  15. Eddard Stark |

    Great! I have a question dough. Ik kan know get the top parent name and the top parent slug. How do i get de top parent ID?

  16. Car insurance claims >> http://onlinecarinsuranceclaims.com/ |

    [… – jzelazny.wpengine.com is other nice place of tips. Online Car insurance claims [… –

  17. Mike D |

    Much thanks for this.

    Change $topParentName = $parentCatListArray[0];
    To Change $topParentName = $parentCatListArray[1];

    and to get the second category down if your in a subcategory.

  18. Antonio |

    This is EXACTLY what i was searching for! Thanks for sharing this snippets.

  19. Jaclyn Schuneman |

    This an Fantastic post, I will be sure to save this in my Reddit account. Have a good day.

  20. Sumeet Chawla |

    Thanks, was quite helpful.. I was going to do the same…

  21. txie |

    It gives me this error:
    “Catchable fatal error: Object of class WP_Error could not be converted to string…”

  22. alvaro |

    Catchable fatal error: Object of class WP_Error could not be converted to string

  23. fabrizio |

    Hi,
    your solution changed the course of a project I’m working on, thank you.
    I have a question: as far as I can understand reading top-category.phps, there’s no way to get top category when in single post, is it right?
    Thanks again

  24. fabrizio |

    Found a solution to make it work even in single post, if anyone’s interested

    cat_name );
    $parentCatList = get_category_parents( $category_id, false, “,” );
    }
    $parentCatListArray = split(“,”,$parentCatList);
    $topParentName = $parentCatListArray[0];
    $sdacReplace = array(” ” => “-“, “(” => “”, “)” => “”);
    $topParent = strtolower(strtr($topParentName,$sdacReplace));
    ?>

    • Schubie |

      Hi Fabrizio,

      unfortunately I canΒ΄t see your whole solution to get the top category on a single page, because it is cropped at the beginning. I am really interested to see your solution.

      Regards,
      Schubie

      • Biccio |

        This is where I ended up so far. I’m everything but a php guru, so I don’t think it’s an elegant solution, but it works πŸ™‚

        if (is_category()) {
        $parentCatList = get_category_parents($cat,false,’,’, true);
        } elseif (is_single()) {
        $category = get_the_category($post->ID);
        $category_id = get_category_by_slug($category[0]->category_nicename );
        $parentCatList = get_category_parents( $category_id, false, “,”, true );
        }
        $parentCatListArray = split(“,”,$parentCatList);
        $topParentName = $parentCatListArray[0];
        $secondParentName = $parentCatListArray[1];
        $thirdParentName = $parentCatListArray[2];
        $sdacReplace = array(” ” => “-“, “(” => “”, “)” => “”);
        $topParent = strtolower(strtr($topParentName,$sdacReplace));

  25. rashida |

    Great article it very informative have a nice day.

    some great stuff im coming across here

    bonds

  26. Robert |

    Please note: This method does NOT work for categories where sub-categories have smaller IDs than their parent categories, because get_category_parents() sorts the categories by their ID – so the first might not be the top category!

    http://codex.wordpress.org/Function_Reference/get_category_parents

  27. jam |

    thanks ! very useful code ! i am using this code to apply to my blog ! and very happy ! it works !

  28. csleh |

    can someone post the code again? the link in the other comment no longer works, and this is what I see in the above post
    "-", "(" => "", ")" => "");
    $topParent = strtolower(strtr($topParentName,$sdacReplace));
    ?>

  29. csleh |

    readable! thank you!

  30. tokidoki2005 |

    add to functions.php:

    function in_parent_category($cats, $_post = null)
    {
    foreach ((array) $cats as $cat)
    {
    $descendants = get_term_children((int) $cat, “category”);
    if ($descendants && in_category($descendants, $_post))
    return true;
    }
    return false;
    }

    Use in template:

    if (in_parent_category(25))
    {
    echo something
    } else {

    }

  31. John |

    Hi
    Thanks for this. Spent the whole day and still produced a rather lumpy solution – then found this one.

  32. Mad Dog |

    Thanks! I spent an hour or so trying supposed solution after solution, some of which are just copies of the same thing. They didn’t work. This did!

Leave a Reply

Your email address will not be published.
*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.