is_dynamic_sidebar()WP 2.2.0

Defines whether the theme supports widgets and whether at least one sidebar has been added to the panel. Conditional tag.

Use this conditional tag in templates to, for example, include a CSS file for widgets only when they are actually active, or to show a placeholder if the user has not added any widgets yet.

Use the function is_active_sidebar() to check for the presence of widgets in the desired widget panel.

No Hooks.

Returns

true|false.

  • true — at least one sidebar contains widgets.
  • false — if there are no sidebars or widgets (even if sidebars are registered).

Usage

is_dynamic_sidebar();

Examples

2

#1 Output a fallback block if no widget has been added

if ( is_dynamic_sidebar() ) {
	get_sidebar(); // standard sidebar
}
else {
	echo '<p>Add widgets in the admin panel.</p>';
}
0

#2 Check the presence of widgets

Display the text if the theme supports widgets:

<?php
if ( is_active_sidebar( 'left-sidebar' ) ) { ?>
	<ul id="sidebar">
		<?php dynamic_sidebar( 'left-sidebar' ); ?>
	</ul>
<?php } ?>

<!-- The theme supports widgets and at least one widget is installed -->
<!-- for the widget panel. Let's display it: -->
<?php if( is_dynamic_sidebar() ){ ?>
	<ul id="sidebar">
		<?php dynamic_sidebar(); ?>
	</ul>
<?php } ?>
0

#3 Checking for a sidebar

To check the presence of sidebars in the plugin code, when you want to connect a widget to a theme, only if there is at least one sidebar, you might need to put a priority on the hook widgets_init, because if you don't put a priority, your function might work faster than at least one sidebar is registered:

add_action( 'widgets_init', 'widget_init_my_widget', 999 );

Notes

  • Global. Array. $wp_registered_widgets The registered widgets.
  • Global. Array. $wp_registered_sidebars The registered sidebars.

Changelog

Since 2.2.0 Introduced.

is_dynamic_sidebar() code WP 6.9

function is_dynamic_sidebar() {
	global $wp_registered_widgets, $wp_registered_sidebars;

	$sidebars_widgets = get_option( 'sidebars_widgets' );

	foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) {
		if ( ! empty( $sidebars_widgets[ $index ] ) ) {
			foreach ( (array) $sidebars_widgets[ $index ] as $widget ) {
				if ( array_key_exists( $widget, $wp_registered_widgets ) ) {
					return true;
				}
			}
		}
	}

	return false;
}