Grow your CSS skills. Land your dream job.

Last updated on:

Add Category Name to body_class

The body_class function is nice for adding a bunch of classes to the body tag that have 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 "nice" name:

add_filter('body_class','add_category_to_single');
function add_category_to_single($classes, $class) {
  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;
}

Comments

  1. Henrique Silvério
    Permalink to comment#

    Good tip! =]

  2. Permalink to comment#

    Just be careful that no category conflicts with an existing necessary body class. A better option would be to add a custom [data-*] attribute on the <body> element, so that it’s separate data

    I.E.

    <body data-category="alternative">
    

    The great thing about [data-*] attributes is that you can still style them with CSS:

    [data-category="alternative"] {
        background-color: pink;
    }
    
  3. Kaela
    Permalink to comment#

    That second argument $class is throwing an error for me. I removed just that argument and this works perfectly.

  4. Jason Carlin
    Permalink to comment#

    I found the same thing as Kaela. Works fine so long as I the $class arg. Thanks very much!

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".