Get Top Parent Category (WordPress)

44

Posted by: Jennifer Zelazny on January 15, 2009

Categorized: Clients, HOWTOs, SDAC Blog, WordPress Logic

Tagged: , ,

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.

44 Responses to “Get Top Parent Category (WordPress)”

  1. Chris M says:

    It just echos out “Object”..

    • Ngqabutho says:

      @ 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 says:

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

  3. f1shman says:

    thanks alot!!
    i was searching for a long time to find such a solution ;)

  4. f1sHMaN says:

    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 says:

    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 says:

    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 says:

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

    • Ngqabutho says:

      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 says:

    This is great! Thank you so much!!!

  8. Sarah says:

    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 says:

    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 says:

    Wow.. Thanks for the list :)

  11. discostrings says:

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

  12. Alen says:

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

  13. mark says:

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

  14. Reino says:

    This works for me! Thanks!

  15. Eddard Stark says:

    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/ says:

    [... - http://www.sandboxdev.com is other nice place of tips. Online Car insurance claims [… -

  17. Mike D says:

    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 says:

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

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

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

  21. txie says:

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

  22. alvaro says:

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

  23. fabrizio says:

    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 says:

    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 says:

      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 says:

        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. [...] WordPress: category parents August 22, 2010 by jerome * While working on a new project with Florian – Metrokit – we needed parents categories to be displayed within single.php after reading a few post on the subject, here is the solution we came up with, largely inspired by this article. [...]

  26. rashida says:

    Great article it very informative have a nice day.

    some great stuff im coming across here

    bonds

  27. Robert says:

    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

  28. jam says:

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

  29. csleh says:

    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));
    ?>

  30. csleh says:

    readable! thank you!

  31. tokidoki2005 says:

    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 {

    }

  32. John says:

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

  33. Mad Dog says:

    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. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>