Archived topic
Possible to put categories & parent categories in body class?
5 replies · Started by Bandara on April 17, 2021
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
Hi there,
climbing the hierarchical tree for categories is quite complicated.
But i did find this GIST that seems to do that:
https://gist.github.com/hearvox/138586b3741b012c2e9378421f4fb209
It also adds them for archives and page parents - which you may not need.
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 :)