How can I get the number of widgets that are active on a specific sidebar? Is there a core function for this?

I want to add a class to each widget on a sidebar based on how many of them are displayed.

Thanks.

4 s
4

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 Reply

Your email address will not be published. Required fields are marked *