Check for Widgets in Widget-Areas
December 6th, 2009 by Frank • WordPress Tutorials • 4 Comments
Welcome 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.
Info
- Published in WordPress Tutorials
- Tags: Advent Calendar, PHP, Theme, Widget, WordPress, WP
- Comment feed | Trackback URL
- read: 3370 | today: 2
- leave a Comment



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
great, thank you.
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.@Justin: Thanks for the tipp!