Count widgets in position and set class

I found an answer on this very site that didn’t come up before in search before @ Get number of widgets in sidebar

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');

This is the code I had to use once I modified it for Twitter Bootstrap 3 in functions.php:

function my_widgets_init() {
    register_sidebar( array(
        'name' => 'bottom',
        'id' => 'bottom',
        'before_widget' => '<div class="">',
        'after_widget' => '</div>',
        'before_title' => '<h3>',
        'after_title' => '</h3>',
    ));
}
add_action( 'widgets_init', 'my_widgets_init' );


// Dynamic Sidebar Positions

    // Bottom
    function cosmos_bottom_sidebar_params($params) {

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

        if ( $sidebar_id == 'bottom' ) {

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

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

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

Leave a Comment