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.

8

You will need to use the ID value returned by $category[0]->category_parent and pass it through get_term(). Example:

$category = get_the_category(); 
$category_parent_id = $category[0]->category_parent;
if ( $category_parent_id != 0 ) {
    $category_parent = get_term( $category_parent_id, 'category' );
    $css_slug = $category_parent->slug;
} else {
    $css_slug = $category[0]->slug;
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *