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' )) { ?>

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *