Add a Post’s Category Name to Body Class in WordPress

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie