Add a Post’s Category Name to Body Class in WordPress
by Bandicoot Marketing on | Posted in Tutorials | 8 comments
I was working with Digibomb on presswork.me and we needed to add the current post’s category name to the body class in order to style the page differently from the others.
All it took was a few lines of code added to the functions.php
file:
function add_category_name($classes = '') { if(is_single()) { $category = get_the_category(); $classes[] = 'category-'.$category[0]->slug; } return $classes; } add_filter('body_class','add_category_name');
With that in place, you should now see a new class at the end of your body tag when you are on a single post or single page.
8 comments for “Add a Post’s Category Name to Body Class in WordPress”