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.
It just echos out “Object”..
@ 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”
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
thanks alot!!
i was searching for a long time to find such a solution π
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
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.
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!
What u want this code is only applicable for single template and category template.
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 is great! Thank you so much!!!
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?
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!!
Did you take a look: http://jzelazny.wpengine.com/downloads/wordpress-logic/top-category.phps (mentioned in the 2nd comment)?
Yes, I did… and it says/shows nothing about how to make it a link.
But I hacked myself a solution. Not ideal, because it’s not entirely dynamic. So, if the site structure ever changes, it will break. But it will do for now.
`<a href="/dish/category/” title=””>`
Oops, tried to page the code in comments, but didn’t work:
Basically, my link structure looks like this:
href=”/dish/category/ECHO BODYID HERE”
Wow.. Thanks for the list π
Thanks! You just saved me some time and frustration in hacking this out myself.
Big thanks ! Your code resolved my need to display banners by category groups (aka parents).
Thank you again !
Thanks for this.Im going to give it a try.
This works for me! Thanks!
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?
[… – jzelazny.wpengine.com is other nice place of tips. Online Car insurance claims [… –
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.
This is EXACTLY what i was searching for! Thanks for sharing this snippets.
This an Fantastic post, I will be sure to save this in my Reddit account. Have a good day.
Thanks, was quite helpful.. I was going to do the same…
It gives me this error:
“Catchable fatal error: Object of class WP_Error could not be converted to string…”
Catchable fatal error: Object of class WP_Error could not be converted to string
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
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));
?>
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
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));
U saved my day, thanks a lot!
This one works like charm……
thanks sir…it is working for me…and i got the solution which i was searching
Great article it very informative have a nice day.
some great stuff im coming across here
bonds
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
thanks ! very useful code ! i am using this code to apply to my blog ! and very happy ! it works !
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));
?>
Take a look now.
readable! thank you!
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 {
}
Hi
Thanks for this. Spent the whole day and still produced a rather lumpy solution – then found this one.
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!