Check for Widgets in Widget-Areas

WordPress-Christmas-06Welcome to our 6th door of our Advent Calendar. :)

If you use widgets in your theme and this also accommodates a variety of hierarchies, you will quickly realize that it really only makes sense to output HTML for the widgets when the widget area is also used by the user.


Ian Stewart, the developer of the Theme-Framework Thematic found an elegant solution, but you can use it even without the framework.
You just need one function, which is similar to the Conditional Tags of WordPress. Put this function in your functions.php of your theme.

function is_sidebar_active($index) {
	global $wp_registered_sidebars;

	$widgetcolums = wp_get_sidebars_widgets();

	if ($widgetcolums[$index])
		return true;

	return false;
}

It uses the output of your widget area, if there is content.

A query could look like this in your template:

<?php if ( function_exists('is_sidebar_active') && is_sidebar_active('sidebar') ) { ?>
	<div id="sidebar">
		<ul>
			<?php dynamic_sidebar('sidebar'); ?>
		</ul>
	</div>
<?php } ?>

The above example loads the content only, if the widget area with the ID sidebar has content, that means if widgets are used in this area.


4 Comments
  1. Chris says:

    Hi,

    thanks a lot for mentioning our code :)

    This snippet was build to prevent a fully styled but empty widgetized area.

    Last month I spoke to Kaspars Dambis the creator of the Widget Context plugin and asked him, if he could support this method with his plugin. The same day about 3 hours later I got a first working copy of his plugin.

    The latest version of his plugin supports the above mentioned code snippets.

    Chris

  2. I've always loved this snippet of code and have used it for quite some time. But, an equivalent of this function was added in WordPress 2.8: is_active_sidebar(). So, there's no need for a custom function any longer.

  3. Michael says:

    @Justin: Thanks for the tipp!

Leave a Reply