
Are you looking for a way to add the post category to the body element classes for single posts? This little snippet will take all the categories assigned to a post and add each of them as a body class with the pattern sgl-cat-{category-name}
.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
add_filter(‘body_class’,’add_category_to_single’,10,2); function add_category_to_single($classes, $class) { if (is_single() ) { global $post; foreach((get_the_category($post->ID)) as $category) { $classes[] = 'sgl-cat-'.$category->category_nicename; } } return $classes; }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: CSS Hero Review: #1 WordPress Theme Customization Plugin.
Great, but you need one correction or the above code will give a fatal error. The hook should have:
add_filter(‘body_class’,’add_category_to_single’,10,2) since you pass in 2 parameters.
Bruce, The world is a beautiful place because of people like you! 😀
Thanks for saving me some time. 🙂