For real though…why doesn’t WordPress have a ‘not-home’ body class?

It’s a question I’ve asked myself many times. For the life of me I can’t figure out why its not in there! Other CMS’s, like Drupal, have this out of the box, but not WordPress. It has a home body class, as well as several other useful body classes, but no not-home body class. So I said to myself “the tyranny and bullshit has gone on long enough” and I did something about it. I’ve come up with a quick little snippet you can add to your theme’s functions.php file to add the ‘not-home’ body class to any WordPress template. It’s one of the first things I do when starting a new project.

But, first, why would you want this? Well, in a lot of the projects I work on for Uptown Studios our designers will have separate styles created in their PSD mockups for the home page elements and the internal page elements. The home page will often times have larger headings to draw more emphasis to the items highlighted on the home page or have different colors to stand out on darker backgrounds. And this is pretty normal I think, but it presents an issue when trying to designate styles for things such as <p>, <h1> through <h6>, and <button> tags on internal pages. So the not-home body class can come in real handy. So without further ado, paste the following into your themes functions.php file to get the not-home body class of your WordPress site.

// Add not-home to body class
function add_not_home_body_class($classes) {
if( !is_front_page() ) $classes[] = 'not-home';
return $classes;
}
add_filter('body_class','add_not_home_body_class');

What we’re doing here is creating a function that hooks into the built in WordPress function body_class and pushing a new value into the $classes array. We’re using the is_front_page() filter to add the body class to all pages except the home page. Sometimes the is_front_page() filter can return inconsistent results from template to template, so if it’s not working as expected you can try the following (note: the following snippet assumes that your home page has the slug of “home”):

// Add not-home to body class
function add_not_home_body_class($classes) {
if( !is_page('home') ) $classes[] = 'not-home';
return $classes;
}
add_filter('body_class','add_not_home_body_class');

You can also take this opportunity to add any other body classes you’d like to the body tag that will only show up on pages that aren’t the front page. I’m not sure what those other classes might be or what you’d need them for but, shit, I don’t know you’re life! Do what you gotta do.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>