search ]

Add Category Name to body_class in WordPress

The body_class function helps add classes to the body tag, which usually contains information about what type of page is currently displayed, and allows you to style specific elements on that page by that specific class.

For some reason WordPress does not add a class describing which category (or categories) you are in on a single post page (e.g. single.php). To add the category name to that body tag, use the following code:

function sv_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;
}
add_filter('body_class','sv_add_category_to_single');

This uses the body_class filter. Learn more in WordPress Hooks Explained.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo