wp_get_sidebars_widgets()
Gets a list of all sidebars (widget panels) and a list of all widgets in those sidebars.
- Uses global variables $_wp_sidebars_widgets, $sidebars_widgets
- Uses the option
sidebars_widgets
Internal function — this function is designed to be used by the kernel itself. It is not recommended to use this function in your code.
Hooks from the function
Returns
Array. An associative array where the key is the ID of the widget panel (sidebar), and the value is an array of all widgets from each panel, including the panel with inactive widgets.
Usage
wp_get_sidebars_widgets( $deprecated = true );
- $deprecated(boolean)
- Not used. The parameter is deprecated.
Default: true
Examples
#1 What the function returns
$wg = wp_get_sidebars_widgets(); /* $wg Array ( [wp_inactive_widgets] => Array ( [0] => text-8 [1] => text-5 ) [sidebar] => Array ( [0] => democracy-2 [0] => text-1 ) ) */
#2 Count the number of widgets in the sidebar
Suppose we need to do something depending on how many widgets are in the panel. For example, there is a horizontal sidebar where you can add any number of widgets. We need to set a different CSS class for each of them depending on their quantity.
For example, if there is one widget in the sidebar, then col-lg-12. If there are two - then col-lg-6.
To do this, we find out the name of the required sidebar, let's say it is sidebar_horizontal.
$wg = wp_get_sidebars_widgets();
$myid = 'sidebar_horizontal';
// the required sidebar exists
if( isset($wg['sidebar_horizontal']) ){
$wgcount = count($wg[$myid]);
$class = 'col-lg-12';
if( $wgcount == 2 ) $class = 'col-lg-6';
elseif( $wgcount == 3 ) $class = 'col-lg-4';
elseif( $wgcount == 4 ) $class = 'col-lg-3';
// set the class via hook
add_filter('dynamic_sidebar_params', function($param) use($class){
foreach( $param as & $data ){
if( $data['id'] == $myid ){
$data['before_widget'] = str_replace('class="','class="'. $class .' ', $data['before_widget'] );
}
}
return $param;
});
}
// output the widgets
dynamic_sidebar('sidebar');
Notes
- Global. Array. $_wp_sidebars_widgets
- Global. Array. $sidebars_widgets
Changelog
| Since 2.2.0 | Introduced. |