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

wordpress

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.

Author Tom Kenny

I'm the creater of Inspect Element and currently work as a web designer for TUI Travel. You can view my portfolio and follow me on Twitter.

Discussion

  1. Sajid Iqbal says:

    Thanks. This is what I was looking for.

  2. Otto says:

    Actually, since WordPress 2.8, there actually is a built in way to do this.

    Change your body tag to look like this:
    [body [?php body_class(); ?] ]

    The body_class function outputs a “class=’whatever’” piece, and the classes it outputs depend on where you are on the site.

    For example, the front page gets “home”, other Pages get “page”, individual pages get page-id-## (where the ## is the id number of the Page), etc.

    A full list of what gets what can be found here: http://wpengineer.com/wordpress-28-body_class-automatic_feed_links/

Become Part of the Discussion

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.