X

How To Add the Post Category to the body_class Function for Single Posts

Snippets by IsItWP

Are you looking for a way to add the post category to the body element classes for single posts? This little snippet will take all the categories assigned to a post and add each of them as a body class with the pattern sgl-cat-{category-name}.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

	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) {
				$classes[] = 'sgl-cat-'.$category->category_nicename;
			}
		}
		return $classes;
	}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: CSS Hero Review: #1 WordPress Theme Customization Plugin.

Comments  Leave a Reply

  1. Great, but you need one correction or the above code will give a fatal error. The hook should have:
    add_filter(‘body_class’,’add_category_to_single’,10,2) since you pass in 2 parameters.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!