Add CSS Class to WordPress Body Tag If Active Sidebar Present

I recently started work on a theme that I wanted to make¬†truly¬†flexible. As part of this I wanted to add a CSS class to the <body> tag of ‘has_sidebar’ in the condition that the site had a sidebar with widgets present (an active sidebar).

I found a few tutorials but they were for old versions of WordPress and didn’t work in the current (3+ versions of WordPress). After a bit of hacking about I managed to get the following code working.

To use, simply add this to your Themes functions.php file:

function has_sidebar($classes) {
  // add 'class-name' to the $classes array
  $classes[] = 'has_sidebar';
  // return the $classes array
  return $classes;
}

if (is_active_sidebar('right_sidebar')) {
  add_filter('body_class','has_sidebar');
}

Following some discussion with some WordPress experts, I now present to you, a new improved version of the above code that moves the conditional inside the function rather than flapping about on its own.

function has_sidebar($classes) {
    if (is_active_sidebar('sidebar')) {
        // add 'class-name' to the $classes array
        $classes[] = 'has_sidebar';
    }
    // return the $classes array
    return $classes;
}
add_filter('body_class','has_sidebar');

It’s also recommended that if you use this code in your own theme that you prefix the function name with the name of your theme (replace all occurrences of ‘has_sidebar’ with ‘yourtheme_has_sidebar’. This just prevents clashes with any other functions contained within plugins.

The updated code has now been merged into all of my currently available themes: Terminally, Hello Sexy and Fiver.


Posted on
by Andy



About Andy

Andy Warburton is a web designer and developer from the UK currently living in Amsterdam, The Netherlands. When he's not building totally awesome WordPress themes or stuffing his face with Sushi, Andy can be found hanging out with his wonderful wife and child. You should totally follow me on Twitter

Leave a Comment

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