Category class in body wordpress

The body_class function is nice for adding a bunch of classes to the body tag that has 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 “upcoming-webinar” name:

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

Leave a Comment

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

0 Shares
Tweet
Share
Pin
Share