Body Class Enhanced for WordPress

I do not request donations for my plugins, but if you find this plugin helpful, please visit the WordPress.org plugin directory and give it a 5-star rating. Thanks!

Summary

Enhances the body_class template tag, adding some extra classes to the body (post/page slugs, post categories, and archive parent categories) useful in developing custom themes.

Description

When activated, this plugin causes the body_class template tag to output five additional classes.

On single posts (is_single) :
postname-[permalink slug]
single-[category slug]
parent-[parent category slug]
(all parent/grandparent categories in a hierarchy of any depth)

On pages (is_page) :
pagename-[permalink slug]

On category archives (is_archive and is_category) :
parent-category-[parent category slug]
(all parent/grandparent categories in a hierarchy of any depth)

Custom Taxonomies

As of version 1.3, the plugin now supports custom hierarchical taxonomies. The new body classes take the following form:

On single posts (is_single) :
single-[taxonomy]-[term slug]
parent-[taxonomy]-[parent term slug]
(all parent and grandparent terms in a hierarchy of any depth)

On taxonomy archives (is_archive and is_tax) :
parent-term-[parent term slug]
(all parent and grandparent terms in a hierarchy of any depth)

For single posts, the taxonomy name is included in the class name, because I felt it was important to be able to distinguish between taxonomies in cases where a post is assigned to more than one custom taxonomy, and when the same term might appear in two or more taxonomies. For example, suppose you had a real estate site with property listings in New York City, and you had two custom taxonomies defined: City and State. Then the classes would look like this:

single-city-new-york single-state-new-york

Multisite Support

As of version 1.3, the plugin now supports multisite installations. If a multisite install is detected, the plugin will output the follow additional body class on every page of the site:

site-[site ID]

Examples

If you have a post titled Top 10 Decorating Ideas, in category Christmas, with a parent category of Holidays and a grandparent category of Calendar, the additional body classes will be as follows:

postname-top-10-decorating-ideas single-christmas parent-holidays parent-calendar

Why is this useful? Because it enables you to style individual posts and pages, as well as entire categories of posts, using only CSS, without having to edit the template files or create new templates.

Continuing the above example, if I wanted to give all of the posts in the Christmas category a green heading (to give them some extra holiday cheer), I could use a CSS selector like this:

body.single-christmas h1 {
color: green;
}

Going further, suppose I want to attach a background image of a Christmas tree only to the “Top 10 Decorating Ideas” post:

body.postname-top-10-decorating-ideas div.post {
background: url('images/xmas_tree.gif') no-repeat left top;
}

What if I want all posts categorized under Holidays (Christmas, Thanksgiving, Easter, whatever) to have a sidebar with a gold border?

body.parent-holidays div#sidebar, /* all posts assigned to a subcategory of Holidays */
body.single-holidays div#sidebar { /* any posts assigned directly to the Holidays category */
border: solid 2px gold;
}

These are just a few examples. If you are experienced in writing CSS selectors, you will find many more uses for the new body classes. For further discussion, see this thread on the WordPress support forum: http://wordpress.org/support/topic/393942

Installation

  • Upload ambrosite-body-class.php to the /wp-content/plugins/ directory.
  • Activate the plugin through the Plugins menu in WordPress.
  • Verify your theme has the body_class function on the body element in header.php:

<body <?php body_class(); ?>>

Frequently Asked Questions

The body_class template tag is already outputting the post and page IDs. Aren’t the slugs redundant?

Yes, the post IDs can be used in CSS selectors. However, the slugs are much easier to remember and use. They will also make the CSS file a lot more readable when you come back to it a month or a year later.

The post_class template tag is already outputting the category slug. Isn’t it redundant to put it on the body as well?

Putting the category slug on the body makes it possible to target elements outside of the post div. For example, if you wanted to style the sidebar on a per-category basis (e.g. change it’s width for all posts in a certain category, or even hide it completely), you could do it using the body class, but not the post class.

Changelog

1.3

  • Added support for custom hierarchical taxonomies.
  • Added multisite support.

1.2

  • Added category archive parent categories.
  • Finds all parent and grandparent categories in a hierarchy of any depth.

1.1

  • Added single parent categories.
  • Added prefix variables for easier customization.

1.0

  • Initial version.

More Plugins

Comments

  1. Tom Tate says:

    Hi. Awesome plugin and very useful for keeping things tidy. My problem is with multisite wordpress. Any idea on how to get it to serve up an ID for each new site’s homepage so I can call CSS for the for each site?
    I figure you are the person to go to for any kind of direction on this. thanks in advance.

    The site I am working on is here. http://www.tatecreate.com/leslykahn/. The offending menu items are top left and point to the 4 blogs attached to the site using wordpress 3.0 multisite.

    -tom

  2. ambrosite says:

    @Tom Tate Thanks for the positive feedback. I do not have any experience with WordPress MU, but now that multi-user has been merged into the core, I’ll look into adding that feature with the next version of the plugin.

  3. Kagen Tres says:

    I love you. I spent hours trying to get a function to work to do just what your plugin does. I’m so glad I stumbled onto your site, it worked perfectly with my wordpress 3.0 install.

  4. ambrosite says:

    @Kagen Tres Thanks for the positive feedback. Of all the plugins I have written, Body Class Enhanced is the one I find most useful in my own projects. I have it installed on every WP site I build. And can you imagine that before WP 2.8, there was no body_class function at all? We have the developers of the Sandbox theme to thank for coming up with the concept, which was eventually merged into the WP core.

  5. Michelle says:

    Hi I am a bit confused about his BodyClass plugin. I am wondering whether you have to / can make a completely seperate CSS file for a page, or whether you have to include the new body tag in the current CSS?

  6. ambrosite says:

    @Michelle You can make a separate CSS file if you want, but it is not necessary. The extra body classes work just like any other CSS classes. To use them, all you have to do is write an appropriate selector. Check out this article if you need more help:

    http://www.nathanrice.net/blog/wordpress-2-8-and-the-body_class-function/

  7. J. Alan says:

    Ambrosite,

    Great plugin. I spent several hours looking before I stumbled across this. I do, however, have a suggestion… Would it be possible to create a plugin (or modifiy this one) that added an “assign a class to this page/post/category” field on the editing screen within wordpress (If you’ve ever seen the back end of the Thesis theme you’ll know what I mean). Where this would be beneficial is you could simply type in the same class for multiple pages, posts, or categories, i.e., if I had 10 pages that I wanted to remove the left side bar from (with a 3 column theme) I could give them all a class of “no_left_sb” and add to my css sheet:

    .no_left_sb #the_left_sidebar_id_goes_here {display:none;}.

    I’d write a plugin that does this myself but I haven’t a clue how to do it. At any rate, I still love your plugin.

    Regards,

    J. Alan

  8. ambrosite says:

    @J. Alan Thanks for the positive feedback. It might be possible to do what you are asking, but it would make the plugin way more complicated than it is now. I think what I would do in your case is make a separate page template for those ten pages.

  9. Al says:

    Great plugin, saved me a lot of time and now I can target posts in specific categories. Nice work

  10. Michelle says:

    Thanks so for much for this fantastic plugin, it works a treat.

  11. ambrosite says:

    I just discovered that Lorelle VanFossen gave Body Class Enhanced a nice mention in her WordPress blog. There is also some good information there on using category classes to style posts:

    http://lorelle.wordpress.com/2007/09/06/using-wordpress-categories-to-style-posts/

  12. Rob says:

    could this plugin be utilized to work with custom taxonomies?

    as it, it seems to work with categories. thus, i can CSS-ify category pages, and posts that fall within that category, as the Ambrosite Body Class Enhanced (ABCE) follows along.

    however, i’m starting to create custom taxonomies. it appears as if i can CSS-ify the main taxonomy page, however the posts within the taxonomy have no record of being in the taxonomy according to ABCE, so the styles don’t follow.

    would it be easy to make it so i could…?

  13. ambrosite says:

    @Rob Yes, it might be possible to extend the plugin to work with custom taxonomies. I am planning to update several of my plugins after WordPress 3.2 is released; I’ll look into making the requested change at that time.

  14. marco says:

    could you include it to work with pages, too? i use a plugin called map-categories-to-pages from http://wordpressable.me/plugins/map-categories-to-pages and managed to add them to be used by adding the following code to version 1.2:

    elseif ( is_page() ) {
    $wp_query->post = $wp_query->posts[0];
    setup_postdata($wp_query->post);
    $classes[] = $page_name_prefix . $wp_query->post->post_name;

    foreach( (array) get_the_category() as $cat ) {
    if ( !empty($cat->slug ) )
    $classes[] = $single_cat_prefix . sanitize_html_class($cat->slug, $cat->cat_ID);
    while ( $cat->parent ) {
    $cat = &get_category( (int) $cat->parent);
    if ( !empty( $cat->slug ) )
    $classes[] = $single_parent_prefix . sanitize_html_class($cat->slug, $cat->cat_ID);
    }
    }
    }
    I hope code isn’t filtered

  15. I was wondering, how difficult is it to create a plugin that would allow you to add a custom body class to a page? Say you had one page that you just wanted to give a specific body class to but not others that it may share body classes with already…

  16. ambrosite says:

    @Trevor The plugin already does that. It puts a unique ‘postname-’ or ‘pagename-’ class on every post and page, so you can use them to target specific pages.

  17. Sasa says:

    Your site works excelent except one problem. If i have structure categories like this,
    1. foo
    1.1. bar
    1.2. baz

    and if i add post in both categoeries bar and baz, i will have twice parent-foo class in body. So, your plugin is not checkinf if class is there already called by first subcat.

  18. ambrosite says:

    @Sasa Yes, you are right about that. I did not consider it a big problem because the classes still work even if some of them are duplicates. However I will try to fix the duplicate classes in the next version of the plugin.

  19. sohbet says:

    Wery nice pluging thanks

  20. Sergio says:

    hello, Ambrosite

    I’m trying to put a background image in the to different categories and would like to put an external link to each image in the background.

    Is it possible?

    Thank you very much for your plugin

    Sergio

  21. Mark says:

    Wonderful plugin!
    Is there a way to apply the category hierarchy to post_class?
    I want to be able to target posts by their parents/grandparents on my frontpage and archive pages. I tried adding “add_filter(‘post_class’, ‘ambrosite_body_class’);” to the end of the code, but didn’t work.

    I’m not expert enough with php to understand what your code is doing?

    Can you point me in the right direction?

    Mark

  22. ambrosite says:

    @Mark There is no simple fix for that. I did consider writing a Post Class Enhanced plugin a while back, but at the time there did not seem to be any reason, since the default post class included most of the features that Body Class Enhanced provided. But now that I have added more features to Body Class Enhanced, it might be worth writing a separate plugin to carry those new features over to the post class. I’ll see if I can find the time to do that next month.

Comments are closed. If you have a question about this plugin, please create a thread on the WordPress support forum and I will answer it there.