Add Category Name to WordPress body class

For styling purposes in WordPress it’s useful to add more information to a page so that you can target specific content. To do this we can use the body_class hook.

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

Adding this code to your functions.php file will add the category name as a class to the body tag.



Leave a Reply