Styling each WordPress page differently
This post is aimed at those who create their own WordPress themes, or who are at least comfortable editing the odd bit of PHP code in an existing theme.
There are often times, when creating a WordPress theme for a site that is more than just a blog, that you want the same elements to be styled a little differently on different pages.
On a hand-crafted, non-WordPress site, you might choose to apply a unique class (you could use an ID instead if you wanted) to the body tag of each page – quite easy when building a custom site, and definitely the logical way to do it. You can then have style definitions such as the following:
body.contact h2 { color:#e21; }
In this example, the only h2 tags that will take that colour are ones on pages whose body tag has a class of contact.
If only you could easily do the same in WordPress!
Well, you can.
In your theme’s header.php file, put the following code before everything else.
<?php
$objPost = $wp_query->get_queried_object();
$intPostID = $objPost->ID;
$strSlug = $objPost->post_name;
$strBodyClass = $strSlug;
if (!is_page()) { $strBodyClass = 'blog'; }
?>
And alter your body tag to:
<body class="<?php echo $strBodyClass?>">
In my example, each WordPress page will have a class equal to the page slug, and all posts (i.e. not pages) will take a class of blog. With some tweaking you could easily change this.



Thank you. I was looking for a solution like this.
And the eagle-eyed among you will have realised that one line of the PHP code is not required for this purpose:
$intPostID = $objPost->ID;
You can safely remove that line. It’s in there because I use the post ID for something else in my theme.
Hey, now with WordPress 2.8 there’s an even easier way! 2.8 has a body_class function, described in loving detail at this URL: http://www.nathanrice.net/blog/wordpress-2-8-and-the-body_class-function/