WordPress 2.8 came out with a bang, offering some great new functions for using in your templates. One of these is called body_class. It’s a simple function you include in the body tag that will automatically add a class to the body tag that is specific to the page you are on. For instance, if you are on a category page, it will add the class “category”. If you are on the home page, it adds the class “home”. It’s easy to implement, and looks like this:[sourcecode language="php"]<?php body_class(); ?>>[/sourcecode]There are a ton of articles out there already about this that deal with adding your own custom classes, one of the best being “>WordPress 2.8 and the body_class() Function“, but I ran into a specific need for a project I’m working on, and wanted to share my solution, since it wasn’t something I had been able to find pre-written.
For this project, I was using the body class to add a specific color to a nav item whenever I was on an active page that fell under that nav item. It was simple to do for pages, but when I got to the pages that I use for custom category listings as discussed in “WordPress: Create a Page Template that Paginates Posts from a Certain Category“, I found out that on a single post, the body_class() function doesn’t add the categories, like it does in post_class(). Furthermore, when I did discover how to add the categories, it didn’t list the parent of that category, which is what I needed. This was the solution I was able to piece together, I hope you find it useful:
<?php $class=''; /* Make it void by default */
if ( is_single() || is_category() ) { /* Only do this if we're on a single post or category page */
$category = get_the_category();
$parent = $category[0]->category_parent;
$class = get_cat_name($parent); /* assign the permalink name for the parent category to the object $class */
}?>
<body <?php body_class($class); /* This will add our custom class, which is void if we aren't on a single post or category page */ ?>>
This is lovely Tammy, it just works!