Paulund
2013-03-25 #wordpress

Check If A Sidebar Has Widgets Assigned

To display a sidebar in your Wordpress site you first need to register the sidebar so that Wordpress can assign widgets to it. When a sidebar is registered it will appear in the widget dashboard so that you can assign widgets to each sidebar. When you have widgets assigned to your sidebar you need to add some code to your theme so it can be displayed on your site. To display a sidebar in your Wordpress theme you need to use the function dynamic_sidebar(), this will allow you to pass in a sidebar id to display the contents of the sidebar. There are times when you will want to check if the sidebar has widgets assigned to it before you include it on the page, this is commonly for styling them correctly.

For example if you are creating a grid layout with your sidebars inside then you need to know which sidebars have widgets before you and them to the page. The following code will use the Wordpress function is_active_sidebar() to decide which sidebars have active widgets so we know what layout to use to display the two sidebars. The is_active_sidebar() function takes one parameter which is the id you give to the sidebar when it is registered, and it will return a boolean value, TRUE if the sidebar has widgets assigned and FALSE if the sidebar has no widgets assigned to it.


function display_sidebars()
{

     if(!is_active_sidebar( 'sidebar-1' ) && !is_active_sidebar( 'sidebar-2' ))
     {
          return false;
     }

     if(is_active_sidebar( 'sidebar-1' ) && !is_active_sidebar( 'sidebar-2' ) || !is_active_sidebar( 'sidebar-1' ) && is_active_sidebar( 'sidebar-2' ) )
     {
          $gridCss = 'col-full';
     } elseif(is_active_sidebar( 'sidebar-1' ) && is_active_sidebar( 'sidebar-2' )) {
          $gridCss = 'col-half';
     }

     if(is_active_sidebar( 'sidebar-1' ))
     {
          ?>
               <div class="<?php echo $gridCss; ?>">
                    <?php dynamic_sidebar( 'sidebar-1' ); ?>
               </div>
          <?php
     }

     if(is_active_sidebar( 'sidebar-2' ))
     {
          ?>
               <div class="<?php echo $gridCss; ?>">
                    <?php dynamic_sidebar( 'sidebar-2' ); ?>
               </div>
          <?php
     }
}