Wordpress Snippets

Add Post Category Slug to Body Class in WordPress

By default WordPress adds many useful classes to body and posts, to help theme developers to style their sites effectively with only CSS and without needing to edit theme files unnecessarily. For example, WordPress adds the category name when you’re viewing an archive page so you can style archive pages differently for each category. But it doesn’t add the post category slug class in body when you’re viewing a single post and sometimes you may find yourself needing to style a particular post differently, based on the specific category that it’s in. This can be an easy way to apply styling to every post that belongs to a category just by adding a bit of styling to your CSS file. So in this article we will show you how to add post category slug to body class.

We will be using body_class WordPress filter to add more classes to HTML body tag. Following is the little function that will add each of post categories to the body class of the single post. In this function we are getting the post category slugs of each category and adding them to body classes array.

Just add this WordPress snippet to your theme’s functions.php file to add post category slug to body classes. That’s all you need to do.

// add post category slug to body class in wordpress
function wcs_add_category_slug_body_class( $classes ) {
    global $post;
    if ( is_single() ) {
        foreach ( get_the_category( $post->ID ) as $category ) {
            $classes[] = $category->category_nicename;
        }
    }
    return $classes;
}
add_filter( 'body_class', 'wcs_add_category_slug_body_class' );

source

Hire Us. Or just say Hi!
Need a job? Apply to get one.