A Handy WordPress Function: body-class()

This feature has been in WordPress since version 2.8 and we’re at 3.31 now, so this won’t be news to some, but either I didn’t need it until recently or had found a way to re-invent the feature well-enough for my purposes, so it’s new to me and valuable enough to deserve comment.

Simple code, just a PHP function inside the HTML body tag, deploys the feature in a WordPress template:

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

The variable $class is an optional space-separated list or array of class names that will be applied as attributes to the body tag when WordPress renders the template. More usefully, though, the method also echoes some WordPress-generated classes that identify the page being viewed, among other useful things.

There’s a long list of these WordPress-generated class names on the WordPress Codex page, but I’ll just illustrate it via the context in which I put it to use.

While adapting a bare scheme I have to meet a client’s requirements, I used a faux-column technique to house a widget-enabled right-sidebar. The client, though, needed an option to remove that sidebar on some pages with wide content (forms that couldn’t easily be changed), so I made the template option “one-column-page.php” which didn’t invoke the sidebar.

Now, using >, selecting that template causes the class “page-template-one-column-page-php” to be added to the body tag and I can use a style-sheet rule to disable the background-image that defines the faux-column:

#pageWrapper {
background-image: url("images/gold_240x10.png");
background-repeat: repeat-y;
background-position: right;

/* Disable faux-column if using one-column-page template. */
body.page-template-one-column-page-php #pageWrapper {
background-image: none;

Had I needed, I could have used the same technique to change the dimensions of page elements to accommodate the additional space created by removing the sidebar. Pretty handy, and that just touches the surface.