In this code snippet we will share how to add category name to body_class in WordPress. If you want to add body class, You need to add some line of code to your theme’s functions.php file.

Add the following code to functions.php file:

/* Add category name to body_class */
add_filter('body_class','wpc_add_category_to_single');
function wpc_add_category_to_single($classes, $class) {
  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;
}
How to Add Category Name to Body Class in WordPress
5 (100%) 3 votes

(Visited 86 times, 1 visits today)

About the Author: Editorial Staff

Editorial Staff at the WPChandra is a team of WordPress experts writing about WordPress Tutorials, Themes, Plugins, Guides, Tricks and much more...

Leave a Reply

Your email address will not be published. Required fields are marked *