Add CSS Class To Single Post Based on Category In WordPress
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
}
?>
Thank You very much!!
This was very useful!!!
Regards
Ale
Happy to be of service, Alessandro!
– John
Hello, would it be possible to do the same thing with custom post rather than post?
Best regards
Marion
Hi Marion:
I don’t have a project where I have this scenario at the moment, however my guess is this snippet would add the class to any post type with the selected category, whether it would be a regular post or a custom post type.
Thanks,
John
Hey, this code add class on single post and on category page too. What if we want only on single post page?
That’s a fair question, Khalid. How I would probably deal with that if it were me is create another header file for your single posts. Add the code snippet in that file, but not to the regular header file. Let’s say that the new file is named
header-singlepost.php.In the template for single posts, you would use this instead of
get_header():That way, you are only calling the code on single posts.
There might be a better way to do this, but this method will work.
– John