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.

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

    1. 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

  1. Hey, this code add class on single post and on category page too. What if we want only on single post page?

    1. 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():

      
      <?php get_header('singlepost'); ?>
      
      

      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

Join the Conversation

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