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.
This is my closest post to what I need.
How can I use this code to show the category in an that contain all information about de post.
I like to do this because I want to create different style for every category that I have.
I try dirrectly put the body_class in the but I don’t need all this informatiocn (home blog logged-in admin-bar no-customize-support wp-custom-logo .category uncategorized) I only need this (uncategorized) because is the category of the post.
It works for me. Thank you!
Interestingly, when I copy the code, the single quote was copied as Chinese single quote “‘’”, I had to manually change it to make it work. I don’t believe it is your problem, still trying to figure out how that happened.
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. 🙂