Get number of widgets in sidebar

After some research and based on the answer from Eugene Manuilov I made a function that adds custom classes to widgets in a specific sidebar (‘sidebar-bottom’ in my case) based on the number of widgets set in that sidebar. This will suit perfectly in horizontal sidebars and themes based on twitter bootstrap that need spanX class to adjust the element’s width.

function cosmos_bottom_sidebar_params($params) {

    $sidebar_id = $params[0]['id'];

    if ( $sidebar_id == 'sidebar-bottom' ) {

        $total_widgets = wp_get_sidebars_widgets();
        $sidebar_widgets = count($total_widgets[$sidebar_id]);

        $params[0]['before_widget'] = str_replace('class="', 'class="span' . floor(12 / $sidebar_widgets) . ' ', $params[0]['before_widget']);
    }

    return $params;
}
add_filter('dynamic_sidebar_params','cosmos_bottom_sidebar_params');

Leave a Comment