Add Category to the Body Class in WordPress

19 Oct 2016
admin
2139
0

WordPress doesn’t include the category in the body classes by default, so stick this in your functions.php and hey presto, the category will be added for each post with a category assigned to it.

function 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;
}

add_filter('body_class','add_category_to_single');