The body_class function is great for adding a bunch of classes to the body tag that has information about what kind of page you are currently viewing, most likely for styling purposes. As a default, it doesn’t include a class for the current category (or categories) for a single post.
The below PHP code adds the category ‘nice’ name, and you can simply add this to your functions.php file:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
We needed to do some specific styling for each of the different categories for single posts and this was a good way to achieve that. Let’s say you had the category ‘Technologies’ and you wanted to make the h1 tags blue. The PHP code above will add the class ‘technologies’ to the body so that you could style all the posts with this category as simple as doing:-
body.technologies {
color: #2581c4;
}.
Pretty simple right?
Hope this helps! Happy coding 😉
HI Nathan,
Love this tutorial and super simple. Appreciate it!
By the way, love your website. It looks great and clean! Well done.
Trevor.
Glad you like it Trevor. It always comes in handy adding category classes to the body tag when you need some customisation.
Thanks for your comment, we value your feedback! 🙂
Hi,
I tried to add this snippet to function.php (copy paste) but it did absolutly nothing.
Am I missing something ?
Are you checking the
body
class on a category page, i.e. post single page? or a CPT with a category?Nope, as FRançois said, it’s not working.
These are the default classes, yes is a single post, none of the cats are being included.
Current clssses:
single
single-post
postid-241580
single-format-standard
logged-in
custom-background
theme-Divi
plg-peepso
dbdb_divi_2_4_up
desktop
woocommerce-no-js
membership-content
access-granted
member-logged-in