Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
Silva Web Designs - Blog

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 😉

 

It’s good to share

5 thoughts on “WordPress – How to add Category Name to the body class

    1. Glad you like it Trevor. It always comes in handy adding category classes to the body tag when you need some customisation.

      Thanks for your comment, we value your feedback! 🙂

Join the discussion