How to detect active widgets in each sidebar

While developing a WordPress theme for a sites network where the built-in calendar widget would be ocasionally included, a special background needed to be applied for the widgets area when the calendar was active, so I needed to detect if the calendar widget was active or not. In this tutorial we will learn how to detect which widgets are active in each sidebar.

Sidebars have an special option stored in database where they have all the information about each widget that is active on each sidebar. This option is sidebar_widgets and you can check it using phpMyAdmin, going to the wp_options table and looking for sidebar_widgets. This is an associative array that looks like:

sidebar_widgets["wp_inactive_widgets"] ➡ all widgets in your WP installation + the active WP theme

sidebar_widgets["primary"] ➡ all widgets active in the primary sidebar, defined by your theme, e.g. “categories-2”

sidebar_widgets["secondary"] ➡ all widgets active in the secondary sidebar, defined by your theme, e.g. “nav-menu-6”

note that I had two sidebars in my theme, you will have more/less keys if you have more/less sidebar areas.

Now that we know where to look for, the following code gets the active widgets on each sidebar and will print all the widgets in the secondary sidebar.

$ilc_widget_active = get_option( 'sidebars_widgets' );
if ( $ilc_widget_active ) {
  foreach( $ilc_widget_active['secondary'] as $widget ) {
    echo '<p>';
    var_dump( $widget );
    echo '</p>';
  }
}

If you change it for $ilc_widget_active["wp_inactive_widgets"] you will get all the widgets available in your WordPress installation plus those of your theme. So if we wanted to know if the calendar was active, we could change the code within the foreach loop for:

$ilc_widget_active = get_option( 'sidebars_widgets' );
$calendar_active = false;
if ( $ilc_widget_active ) {
  foreach( $ilc_widget_active['secondary'] as $widget ) {
    if ( 'calendar' == substr( $widget, 0, -2 ) ) {
      $calendar_active = true;
      break;
    }
  }
}

Then it’s just a matter of checking if the $calendar_active variable is true or false to know if the calendar widget is active or not. That concludes this week’s tutorial, have fun wordpressing!

6 thoughts on “How to detect active widgets in each sidebar”

  1. Very clever use of the database options, guess I’ll have to dig deeper on the options available.

  2. Because the function is_active_widget() is intended to be used for a completely different task. It allows you to query only if an specific widget is installed. With the code in this tutorial, you get all the currently active widgets to perform any query with them.

Leave a Reply to Chris Cancel reply