Conditional check for active sidebar in WordPress

October 31, 2011 by fMajakovskij

After a lot of search on how to get is_active_sidebar() works, here the tip that just works.

If you need to check whether a particular sidebar is active (means has at least one widget registered) you should put on your theme the following code:

if( is_active_sidebar('alternate-sidebar') )
{
	// print something
}else{
	// do other or nothing
}

Where ‘alternate-sidebar’ is NOT the name of your widget but the ID. It definitely doesn’t work with the name, contrary the documentation.

So when you register a widget in your function.php, you must set either a sanitized ID, pretty like:

register_sidebar(array (
	'name'=>"My Beautyful Name",
	'id'=>"my-beautyful-name",
	'before_widget' => '<div id="%1$s" class="sidemenu %2$s">',
	'after_widget' => '</div>',
	'before_title' => '<h3>',
	'after_title' => '</h3>',
	));

For example if you are going to create multiple sidebar in a smarter manner, you should write something like:

function theme_widgets_init()
{
	$widgets = array('Main Sidebar', 'Optional Sidebar');
	for($i=0;$i<count($widgets); $i++)
	{
		$id = str_replace(" ", "-", strtolower($widgets[$i]));
		register_sidebar(array (
			'name'=>$widgets[$i],
			'id'=>$id,
			'before_widget' => '<div id="%1$s" class="sidemenu %2$s">',
			'after_widget' => '</div>',
			'before_title' => '<h3>',
			'after_title' => '</h3>',
			));
	}
}
add_action( 'init', 'theme_widgets_init' );

And you should use the sanitized id to check if a sider is active.

Hope this help

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=""> <strike> <strong>