wp_get_sidebars_widgets()
Retrieve full list of sidebars and their widget instance IDs.
Will upgrade sidebar widget list, if needed. Will also save updated list, if needed.
This is an internal function for using it by WP core itself. It's not recommended to use this function in your code.
Hooks from the function
Return
Array
. Upgraded list of widgets to version 3 array format when called from the admin.
Usage
wp_get_sidebars_widgets( $deprecated );
- $deprecated(true|false)
- Not used (argument 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 [auto-translate]
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 a custom number of widgets. We need to set a different css class for each of them depending on their number.
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, find out the name of the desired sidebar, let it be sidebar_horizontal.
$wg = wp_get_sidebars_widgets(); $myid = 'sidebar_horizontal'; // the sidebar we need 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'; // put a class through the 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; }); } // display widgets dynamic_sidebar('sidebar');
Notes
- Global. Array. $_wp_sidebars_widgets
- Global. Array. $sidebars_widgets
Changelog
Since 2.2.0 | Introduced. |