Last Updated: February 25, 2016
·
2.379K
· etienne_tremel

Responsive Widgets: automatically inject grid column class

It can be a pain for a WordPress theme developer to tell the user not to add or remove a widget from a horizontally oriented sidebar using a responsive grid system.

Here is some code to automatically inject column class into the widget opening tag. It also adjust the class col-* columns. This prevent the user to break your beautiful and responsive layout.

Copy/past the following code into your functions.php:

<?php
/**
 * Inject Grid column into each widgets
 */
function widget_col_class( $params ) {

    // Column in you grid:
    $grid_columns = 12;

    // Check if we are injecting the right sidebar, replace 'Sidebar' by the sidebar name you want
    if ( $params[0]['name'] == 'Sidebar' ) {

        // Get sidebars
        $the_sidebars = wp_get_sidebars_widgets();
        $widgets = count( $the_sidebars[ $params[0]['id'] ] );

        // Compute number
        $col = $grid_columns / $widgets;

        // Inject the new class
        $params[0]['before_widget'] = preg_replace('/(class=")/', 'class="col-' . (int)$col . ' ', $params[0]['before_widget']);
    }

    return $params;
}
add_filter( 'dynamic_sidebar_params', 'widget_col_class' );
?>

Which will return into your sidebar area something like that:

<div id="sidebar" class="row">
    <div id="my-widget-1" class="col-4 widget-menu">
       ...
    </div>
    <div id="my-widget-2" class="col-4 widget-menu">
       ...
    </div>
    <div id="my-widget-3" class="col-4 widget-menu">
       ...
    </div>
</div>

Enjoy!