Add Post Categories to the Body Class in WordPress

Sometimes you may find yourself needing to style a particular post differently, based on the category that it’s in. Here’s a little function that will add each of a post’s categories to the body class of the single post page (assuming your theme uses the body_class template tag):

function pn_body_class_add_categories( $classes ) {
	// Only proceed if we're on a single post page
	if ( !is_single() )
		return $classes;
	// Get the categories that are assigned to this post
	$post_categories = get_the_category();
	// Loop over each category in the $categories array
	foreach( $post_categories as $current_category ) {
		// Add the current category's slug to the $body_classes array
		$classes[] = 'category-' . $current_category->slug;
	// Finally, return the $body_classes array
	return $classes;
add_filter( 'body_class', 'pn_body_class_add_categories' );

Just add this code to your theme’s functions.php file, or better yet, add it to a child theme or custom plugin so that your changes won’t be overwritten in a theme update.

There is another nice little tutorial on this subject by c.bavota, but it only works for the first category assigned to a post. Subsequent categories are ignored. That’s not a problem if you’ll never have more than one category assigned to each of your posts, but if a post could have several categories assigned to it, you’ll want to use the function I posted here.

10 thoughts on “Add Post Categories to the Body Class in WordPress

  1. This great! It’s exactly what I was looking for to get posts to use the same styles as the category pages they fell under. Thanks!

  2. Pingback: Add Post Categories to the Body Class in WordPress | harucode

Leave a Reply

Your email address will not be published. Required fields are marked *