Collapsing WordPress Widget-Ready Areas & Sidebars

Problem: Theme users need as many widget-ready areas as possible. They’re easy to use and they help keep theme template files clean. But! unused, empty, widget-ready areas, areas waiting for you to add a widget of your choice, hang around waiting to spoil your designs by limiting your styling options. Just as bad, empty widget areas can invalidate your markup. But don’t worry, we can do something about it. Only first, we need to take a closer look at the problem.

Here’s how a typical widget-ready sidebar looks. I’ve taken the code from Automattic’s guide to widgetizing WordPress themes.


We’ve got an unordered list and inside of it a statement that looks for the dynamic_sidebar() function. If we’ve registered one, it’ll spit out our awesome stuff: WordPress widgets marked up as list items.

All very good. But what if we start out with no awesome stuff in there? No default widgets? Well, that means our containing ul element will be hanging out there in our site with no li elements in it. A list without list items. Totally invalid and totally unsemantic. Worse yet: what if you were styling that ul with a margin, border, or just positioning it? That styling would stick—even if the widget area was empty. Totally unacceptable.

Thankfully, there’s a fix.

// Check for widgets in widget-ready areas http://wordpress.org/support/topic/190184?replies=7#post-808787
// Thanks to Chaos Kaizer http://blog.kaizeku.com/
function is_sidebar_active( $index = 1){
	$sidebars	= wp_get_sidebars_widgets();
	$key		= (string) 'sidebar-'.$index;

	return (isset($sidebars[$key]));
}

Blogger Avice (Chaoskaizer) De’véreux came up with the nifty little function above, is_sidebar_active(), in response to a question in the WordPress support forums. It’s a beaut. With it you can check to see if there are widgets in a sidebar and if not, well, you can do something else. Like nothing for an example. Nothing, in this case, is really something.

Here’s an example of the code from the beginning of this post, modified to produce no widget-ready area by default and load one only if there is a widget added to it.

'. "\n";
            dynamic_sidebar();
            echo '' . "\n";
        } ?>

Now, where would this be useful? Well, Thematic is going to start making use of it. With 13 widget-ready areas and only two containing widgets by default, it was in desperate need of this technique. Here’s how Thematic is using is_sidebar_active() in it’s footer to only create a containing div for a group of 3 widget-ready areas if a widget is loaded into any one of them.


    
    
'. "\n" . '
    ' . "\n"; dynamic_sidebar(3); echo '
' . "\n" . '
'. "\n"; } ?> '. "\n" . '
    ' . "\n"; dynamic_sidebar(4); echo '
' . "\n" . '
'. "\n"; } ?> '. "\n" . '
    ' . "\n"; dynamic_sidebar(5); echo '
' . "\n" . '