Add a Category and Page Specific Class to the Body Tag in WordPress

by Tom Kenny (@tkenny)


WordPress is a powerful CMS, especially for blogging but what if you want to style something on a single page and not affect anything on other pages? There isn’t built-in way to do this so we need to use the platform that WordPress runs on by writing some custom PHP.

<?php if (is_home()) { ?>
<body id="home">
<?php } else if (is_category('articles')) { ?>
<body id="articles">
<?php } else if (is_category('offers')) { ?>
<body id="offers">
<?php } else if (is_category('general')) { ?>
<body id="general">
<?php } else if (is_page('about us')) { ?>
<body id="about">
<?php } else if (is_page('contact us')) { ?>
<body id="contact">
<?php } ?>

Above you can see a big if else statement that will assign and id to the <body> tag depending on what page or category the user is viewing. Now we can target specific pages for styling in the CSS.

body#offers p { color: red; }
body#about p { color: green; }
body#contact p { color: black; }

This is a very simple example but you can go more complex such as having different colours for a navigation bar within different sections or change layout on one page without affecting any other pages.

Design Inspiration from the World's Best Designers

Learn why the best designers make the decisions they do to design successful websites people love in this FREE eBook with 3 in-depth case studies. I’ve spent hours studying what makes these websites amazing, so you can use what works and focus on your design work. Subscribe now to get it immediately.

100% privacy. No spam. Completely free!

by Tom Kenny

I’m a freelance web designer and front-end developer with over 7 years of experience designing for the web. Follow me on Twitter here.