Adding category classes to body tag

Written on March 18, 2014

Trying to add category classes was a bit tedious. I ran across a few blog posts on how to implement them. Many didn’t work (maybe they were for previous versions of WordPress?), but one did.

What worked

add_filter('body_class','add_category_to_single');

function add_category_to_single($classes) {
  if (is_single() ) {
    global $post;
    foreach((get_the_category($post->ID)) as $category) {
      echo $category->cat_name . ' ';
	  
      // add category slug to the $classes array
      $classes[] = 'category-'.$category->slug;
    }
  }
  // return the $classes array
  return $classes;
}

Reference: jackreichert

What did not work

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) {
      echo $category->cat_name . ' ';
      
      // add category slug to the $classes array
      $classes[] = 'category-'.$category->slug;
    }
  }
  // return the $classes array
  return $classes;
}

This looks REALLY close to the working code, but the function properties includes a second function value, “$class”, which outputs the following error:

Warning: Missing argument 2 for add_category_to_single() in /home/tonguet1/public_html/wp-content/themes/TTM/functions.php on line 6
News class="single postid-493 logged-in category category-news">

Not sure what’s happening there, but just remove that second value.

This also didn’t work

<body id="top" <?php if (function_exists('body_class')) body_class('category-'.$class ); ?>

Instead of adding the category class, it just adds “category-“ so it isn’t really helpful. If you use this along with the snippet posted above, it will add an additional class of “category” which again, isn’t helpful.

Hope this helps everyone else from spending 15min searching for the right code.