Nowadays, many WordPress themes use horizontal sidebar areas or footer areas, not only a classic WordPress right or left vertical sidebars. This is good because theme users get more flexibility when they add content into their websites. But, developers must keep in mind that they sometimes need to provide specific widget behavior or styling depending of the place of a widget in some specific sidebar area.
Most common case scenario is a horizontal footer sidebar area, so what we are going to show here is how we can add “last” class to the last footer widget. You can of course use this example to modify it by your needs.
Introducing “dynamic_sidebar_params” filter
Any time your theme template files call dynamic_sidebar() function, it will be used to display all widgets assigned to a specific sidebar. WordPress uses dynamic_sidebar_params filter which will be called before any widget is displayed so you can use it to dynamically modify any widget.
Imagine that you have registered a sidebar for your theme footer which fits three widgets in one row. In the following example, we are going to show you how can you add last class to every third WordPress footer widget so you can style this widgets to fit the theme design. Just place this simple snippet inside your functions.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /* Add dynamic_sidebar_params filter */ add_filter('dynamic_sidebar_params','footer_widgets'); /* Register our callback function */ function footer_widgets($params) { global $footer_widget_num; //Our widget counter variable //Check if we are displaying "Footer Sidebar" if(isset($params[0]['id']) && $params[0]['id'] == 'footer_sidebar'){ $footer_widget_num++; $divider = 3; //This is number of widgets that should fit in one row //If it's third widget, add last class to it if($footer_widget_num % $divider == 0){ $class = 'class="last '; $params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']); } } return $params; } |
Hope this helps, feel free to leave your comments below!