Site logo

Archived topic

Possible to put categories & parent categories in body class?

5 replies · Started by Bandara on April 17, 2021

Viewing posts 1–6 of 6

Hello!

Using this code from Tom found here: https://wordpress.org/support/topic/category-class-in-single/#post-11720226

add_filter( 'body_class', function( $classes ) {
    if ( is_single() ) {
        global $post;

        foreach( ( get_the_category( $post->ID ) ) as $category ) {
            $classes[] = 'category-' . $category->slug;
        }
    }

    return $classes;
} );

I am able to add classes specific to categories on single post pages. That works perfectly. However, I'm wondering if there is a way to also add any parent categories. So for example if these were my categories:

—Sports
——Soccer
——Rugby

Then posts categorized as Rugby would get classes category-sports and category-rugby

Wow. You folks are awesome. Thank you so much.

I'm curious when you say

climbing the hierarchical tree for categories is quite complicated.

Does this mean that I should be worried about using the code? Or just that generally it's a tricky thing to do but for this case it seems to be possible? Just curious.

Nothing to worry about - its just a bit tricky getting your head around navigating up a level especially if there are multiple category terms on a post and they could have different parents. Which is why i looked for one someone had already made lol

Thanks so much for finding it.

No problems :)

This archived topic is closed to new replies.