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```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

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