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.

Improve your design knowledge in just a minute or two a day, for free


You'll get a free email every Monday to Friday with actionable design details that will increase the effectiveness of your designs. Each one only takes about a minute or two to read.

Free. No spam. Unsubscribe anytime.

by Tom Kenny

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