Treehouse: 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

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```