Tutorial Add Category Name to body_class

by in , 0

The body_class function is nice for adding a bunch of classes to the body tag that have information about what kind of page is currently being displayed. Probably for styling purposes. But for whatever reason, it doesn't include a class for the current category (or categories) for a single post.

This adds that category "nice" name:

add_filter('body_class','add_category_to_single');
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;
}

Leave a Reply