Mark Thomas Miller

Add CSS class to WordPress posts based on category

If you have multiple categories of posts and want each to be styled slightly differently, this is the article for you. There are a lot of solutions for this kind of problem, but they’re way too bulky if you only want to make a few simple changes.

I found an easy fix. Find your theme’s <body> tag (which is probably in your header.php file) and put this piece of code (that kinda looks like a Metroid enemy below it:

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

No editing necessary.

Then, just close that div with </div> right above your closing </body> tag (which you can probably find in your footer.php file).

Now, when you’re editing your post, give it a category. WordPress will now add your category as a class to the Metroid-looking div. It comes in the shape of category-yourcategoryname. For instance, if you gave your post the category zephy, WordPress would output the following code:

    <div id="post-77" class="post-77 post type-post status-publish format-standard hentry category-zephy"
        ...your post content...

You can now use the CSS element element selector to style elements on those pages. Put this CSS into your theme’s stylesheet or use a custom CSS plugin.

For those of you who are a little rusty on CSS, this means that you put the parent first (.category-zephy), then a space, then the element you want to style (like p). For instance, if my HTML was…

<div class="buzzfeed">
    <h1>10 goats that you really won't believe</h1>
    <p>Like ohmygosh how can #9 do that?</p>
<p>This element won't be styled.</p>

…then I could use the following CSS to style the elements inside the buzzfeed div without affecting the trailing paragraph:

.buzzfeed h1 { color: #cc0000; }
.buzzfeed p  { line-height: 150%; }

Stay beautiful, readers.