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:

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;


  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


    <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

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

<div>Example code</div>

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

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