body_class() for WordPress Theme Designer

I just upgraded my WordPress engine to the latest version. This new version offers some improved and new features. One of them is about body_class() function. Nathan Rice has a definition about this:

The body_class() function operates in nearly the exact same manner as the post_class() function that was introduced in WordPress 2.7. The only differences are the classes it generates. The body_class() function will generate the classes mostly based on where your viewer is on your site.

I used post_class() when it was introduced in WordPress 2.7. This body_class() new function is a great addition for WordPress theme designers. Well, actually it’s not only for WordPress Theme designers, but it’s more for those who want to have/do more on the template. We can have some automatically generated HTML tags like these:

  • <body class="single postid-12">, or
  • <body class="page page-id-9 parent-page-id-0 page-template-default">, or
  • <body class="page-template page-template-tutorial-php logged-in">

See the patterns? Jump to Nathan Rice’s blog posts to read more details. In short, if you want to use this function, just modify your <body> tag. Change it into <body <?php body_class(); ?>>. That’s it!

Join the Conversation

5 Comments

  1. Hi, i’m having trouble understanding how to leverage the body_class function using css.
    My understanding is that in 2.8 and up, the body class is dynamically generated. So if my page is titled About, and my blog page is titled News, the classes .about and .news will be generated.
    if that is the case, i would assume the following css would work – but it doesn’t:
    body.about {background: orange;}
    body.news {background: red;}
    what am i doing wrong? why doesn’t this css work (note: i’m using a clean kubrick theme install)
    thank you for your help regarding this matter.

Leave a comment

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