Body classes on WordPress pages

I spent hours this weekend trying to apply a different body class to a WordPress page. Specifically, I wanted to apply a different class to WordPress pages as opposed to WordPress posts. Why? Because I wanted to be allow comments to be left on a number of pages which were previously outside WordPress, but I wanted the menu, in line with the rest of my site, to display the submenu for either web pages or photo pages, depending on the actual page displayed. My css controls this by using the body class.

Once I’d worked it out it was straightforward, inevitably. First off, I used the “Custom Fields” functionality to define a custom field called bodyclass, then set this to “web” or “photo” as my css requires. Easy so far.

I then amended header.php using WordPress conditional comments to use the bodyclass value for pages, and to use “blog” as standard for posts. The following statement did the trick here:

<body class="
<?php if (is_page()) echo get_post_meta($post->ID, 'bodyclass', true); 
else echo "blog";?>
">

Tags:

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.