WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
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 😉

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

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! 🙂

  1. Nope, as FRançois said, it’s not working.

    These are the default classes, yes is a single post, none of the cats are being included.

    Current clssses:
    single
    single-post
    postid-241580
    single-format-standard
    logged-in
    custom-background
    theme-Divi
    plg-peepso
    dbdb_divi_2_4_up
    desktop
    woocommerce-no-js
    membership-content
    access-granted
    member-logged-in

Join the discussion