
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!