My theme has styling by category using the following code, which inserts the current category’s slug as a CSS class.
<div class="CategorySpecificStyle
<?php $category = get_the_category(); echo $category[0]->slug; ?>">
<?php echo $category[0]->cat_name; ?>
</div>
Now i’m about to add a large number of new sub-categories, and it seems silly to add them all in CSS when I should be able to just select the parent category of the current post and apply styles to that.
I’ve been able to get the parent category’s name:
$parentcat = get_cat_name($category[0]->category_parent);
But spaces (and capitalization) is an issue… And I can’t seem to get the parent category’s slug.
I know i’m probably missing a simple step somewhere, but any insight would be greatly appreciated.
You will need to use the ID value returned by
$category[0]->category_parent
and pass it throughget_term()
. Example:You will need to query for the parent category data.
get_category
is pretty much built for doing that.That will return the immediate parent of the category. That is given this set of categories:
The code above will return “Dog” if you give it the ID for “Scooby”. If you want the topmost parent category– “Cartoon”– no matter how deep the nesting, use something like this:
That also has the advantage of relatively neat error handling.
I found most of the above did not work for Custom Post Types. So I wrote the following function.
Given the ID of the current ( child ) category, it works its way up the chain to give the parent(s) of the category.
It returns an array containing url, name, slug and id of parents.
For example. In a tree of Home>Products>Platic-Bags>Poly-Bags>3muBags
Where the child / current category is 3mu it returned the following:
I like the previous answer from @s_ha_dum, but for getting the top-level category regardless of depth, I used what I consider to be a simpler solution:
If it can help somebody… to get child cat or parent, depending on the
0
or1
you put on the$category
You can simplify it like this:
The following function is adapted to return the root category:
Usage:
get_root_category()->slug
All the answers above are good except the “category_parent” now replaced with “parent” from 2018!
In 2021
For Taxonomies in 2021