Add post category to body_class on single posts

NextGen gallery

This little snippet will take all the categories assigned to a post and add them to the body_class "sgl-cat-{category-name}".

	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;

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!