Blog: WordPress
Female web developer working

Add CSS Class To Single Post Based on Category In WordPress

Avatar for John Locke

John Locke is a SEO consultant from Sacramento, CA. He helps manufacturing businesses rank higher through his web agency, Lockedown Design & SEO.

Here’s how to add a CSS class to the body tag of a single post or post type, based on the post category, in WordPress.

Why would you want to do this?

Maybe you want to add custom CSS styles to single posts in specific categories, but you don’t want to create a custom template for that category.

By adding a CSS class to the body tag, you can make it easier to apply some custom styles to single post types in specific categories.

Here’s two examples of how you could do this.

You would add these to your template files, in the header.php file.



<?php

$post = $wp_query->post;

if ( in_category('categoryone', $post->ID) ) { ?>
    <body <?php body_class('class-name-one'); ?>> 
<?php
} 

elseif ( in_category('categorytwo', $post->ID) ) { ?>
    <body <?php body_class('class-name-two'); ?>> 
<?php
} 

else { ?>
    <body <?php body_class('class-name-generic'); ?>>
<?php
	}
?>

Here’s the same thing, with just different class names.



<?php

$post = $wp_query->post;

if ( in_category('categoryone', $post->ID) ) { ?>
    <body <?php body_class('class-name-one'); ?>> 
<?php
} 

elseif ( in_category('categorytwo', $post->ID) ) { ?>
    <body <?php body_class('class-name-two'); ?>> 
<?php
} 

else { ?>
    <body <?php body_class('class-name-generic'); ?>>
<?php
	}
?>

Avatar for John Locke

John Locke is a SEO consultant from Sacramento, CA. He helps manufacturing businesses rank higher through his web agency, Lockedown Design & SEO.

2 comments on “Add CSS Class To Single Post Based on Category In WordPress

Join the Conversation

Your email address will be kept private. Required fields marked *.