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’,10,2);
	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. This is my closest post to what I need.
    How can I use this code to show the category in an that contain all information about de post.
    I like to do this because I want to create different style for every category that I have.
    I try dirrectly put the body_class in the but I don’t need all this informatiocn (home blog logged-in admin-bar no-customize-support wp-custom-logo .category uncategorized) I only need this (uncategorized) because is the category of the post.

  2. It works for me. Thank you!
    Interestingly, when I copy the code, the single quote was copied as Chinese single quote “‘’”, I had to manually change it to make it work. I don’t believe it is your problem, still trying to figure out how that happened.

  3. 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.

    1. Bruce, The world is a beautiful place because of people like you! 😀
      Thanks for saving me some time. 🙂

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!