Support » Themes and Templates » Add Category “class” to Body of Single Page

  • Resolved Jack Reichert


    If there was a category-cat_name class added to single posts it would be really helpful for designers. I enjoy a little variety and being able to easily style all the posts in each category differently would be really sweet.

Viewing 3 replies - 1 through 3 (of 3 total)
  • That can be done in your theme. I don’t think, natively, WP adds any classes.


    I’ve worked out a solution, but think it would be great if the functionality were added to the body_class() tag.

    Here’s my solution:

    <?php if (is_single()) {
    		global $post;
    		$cats = get_the_category($post->ID);
    		foreach ( $cats as $c ) {
    			$cat .= $c->category_nicename.' ';
    } ?>

    Add the code above to the header.php file before the </head> tag

    <body <?php body_class($cat); ?>>

    Switch the code above with your <body> or <body <?php body_class(); ?> tag.

    Note: if the <body> tag is not in the header.php file you will need to make the $cat variable global.
    (HINT: here’s how… change the line in the code for the header
    global $post; to global $post, $cat;
    change the body tag to this: <body <?php global $cat; body_class($cat); ?>>
    you only need to do this if the <body> tag is not in the header.php file.)

    Still, I think that it should be worked into the body_class() function.

    Here’s a more elegant solution pointed out to me by Chris Coyier, submitted by eastwoodarts here:

    function add_category_to_single($classes, $class) {
    	if (is_single() ) {
    		global $post;
    		foreach((get_the_category($post->ID)) as $category) {
    			// add category slug to the $classes array
    			$classes[] = $category->category_nicename;
    	// return the $classes array
    	return $classes;

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add Category “class” to Body of Single Page’ is closed to new replies.