is_active_widget()
Whether widget is displayed on the front end.
Either $callback or $id_base can be used $id_base is the first argument when extending WP_Widget class Without the optional $widget_id parameter, returns the ID of the first sidebar in which the first instance of the widget with the given callback or $id_base is found. With the $widget_id parameter, returns the ID of the sidebar where the widget with that callback/$id_base AND that ID is found.
NOTE: $widget_id and $id_base are the same for single widgets. To be effective this function has to run after widgets have initialized, at action init or later.
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
No Hooks.
Return
String|false
. ID of the sidebar in which the widget is active, false if the widget is not active.
Usage
is_active_widget( $callback, $widget_id, $id_base, $skip_inactive );
- $callback(callable|false)
- Widget callback to check.
Default: false - $widget_id(string|false)
- Widget ID. Optional, but needed for checking.
Default: false - $id_base(string|false)
- The base ID of a widget created by extending WP_Widget.
Default: false - $skip_inactive(true|false)
- Whether to check in 'wp_inactive_widgets'.
Default: true
Examples
#1 Check if the Calendar widget is active
$sidebar_id = is_active_widget( 0, 0, 'calendar' ); if( $sidebar_id ){ echo 'There is an active Calendar widget in the front'; }
#2 Search in inactive widgets
Suppose we have a 'Text' widget, but it is not in any sidebar, and lies in an inactive area in the admin panel.
$sidebar_id = is_active_widget( 0, 0, 'text', 0 ); echo $sidebar_id; // wp_inactive_widgets
#3 Only load a script when the widget is active
add_action( 'wp_enqueue_scripts', function(){ if ( is_active_widget( false, false, $id_base, true ) ) { wp_enqueue_script( 'jquery' ); } } );
Notes
- Global. Array. $wp_registered_widgets
Changelog
Since 2.2.0 | Introduced. |