WordPress – How to add Category Name to the body class

The body_class function is great for adding a bunch of classes to the body tag that has information about what kind of page you are currently viewing, most likely for styling purposes. As a default, it doesn’t include a class for the current category (or categories) for a single post.

The below PHP code adds the category ‘nice’ name, and you can simply add this to your functions.php file:


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

We needed to do some specific styling for each of the different categories for single posts and this was a good way to achieve that. Let’s say you had the category ‘Technologies’ and you wanted to make the h1 tags blue. The PHP code above will add the class ‘technologies’ to the body so that you could style all the posts with this category as simple as doing:-


body.technologies {
    color: #2581c4;
}.

Pretty simple right?

Hope this helps! Happy coding 😉

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development and web site design. His expertise is WordPress & Magento as well as many other frameworks. Would you like to work with Nathan? Send him an email on [email protected]

It’s good to share