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:<?php body_class(); ?>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:

    $class = get_cat_name( $parent ); /* assign the permalink name for the parent category to the object $class */


One thought on "How to Add the Parent Category as a Class in body_class()"

  1. Sam says:

    This is lovely Tammy, it just works!

Leave a Reply

Your email address will not be published. Required fields are marked *