Sometimes you may find yourself needing to style a particular post differently, based on the category that it’s in. Here’s a little function that will add each of a post’s categories to the body class of the single post page (assuming your theme uses the body_class template tag):
function pn_body_class_add_categories( $classes ) { // Only proceed if we're on a single post page if ( !is_single() ) return $classes; // Get the categories that are assigned to this post $post_categories = get_the_category(); // Loop over each category in the $categories array foreach( $post_categories as $current_category ) { // Add the current category's slug to the $body_classes array $classes[] = 'category-' . $current_category->slug; } // Finally, return the $body_classes array return $classes; } add_filter( 'body_class', 'pn_body_class_add_categories' ); |
Just add this code to your theme’s functions.php file, or better yet, add it to a child theme or custom plugin so that your changes won’t be overwritten in a theme update.
There is another nice little tutorial on this subject by c.bavota, but it only works for the first category assigned to a post. Subsequent categories are ignored. That’s not a problem if you’ll never have more than one category assigned to each of your posts, but if a post could have several categories assigned to it, you’ll want to use the function I posted here.
This great! It’s exactly what I was looking for to get posts to use the same styles as the category pages they fell under. Thanks!
Do you know how to apply this to child categories so that they will include the parent category in the body classes?
Pingback: Add Post Categories to the Body Class in WordPress | harucode
Very, very nice stuff, thnx a ton!
Question: how can this be done with the categories of a portfolio item?
Cheers,
Marc
Thanks a lot! Working perfectly!
THX BRO
want to display only one category class into body
Thank you, exactly what I needed!
Thank you! Especially the explanations in the code helped me to understand, how the code works.
Thanks man! It’s working properly.