04 Oct Making Smart Widgets in a Grid Layout
For those of you who like to use a Grid system in your themes, here is a neat trick I use. Instead of hard coding your widgets i.e. featured-a, featured-b, you could make one widget called ‘featured’ and have it determine the correct layout. You can use ‘wp_get_sidebars_widgets()’ to count how many widgets the user has activated in that spot to dynamically alter your grid width. If the user has 2 widgets activated in ‘featured’, then the grid width would change to 6 in a 12 column layout. If the user has 4 items activated, then it would change to a grid width of 3. Here is an example using Bootcamp’s scaffolding for the grid system.
1 2 | //in your themes functions, register your widget id's in an array $widgets_array = array('featured','footer','top'); |
Adding your widgets in an array will save you the effort of writing out each widget, we will load it in a foreach loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //REGISTER WIDGETS foreach($widgets_array as $key) { $the_sidebars = wp_get_sidebars_widgets(); $span = calc_span(count( $the_sidebars[$key] )); register_sidebar(array('name'=> ucwords(str_replace("-"," ",$key)) , 'id' => $key , 'before_widget' => '<div id="%1$s" class="widget %2$s span'.$span.'">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', )); } |
First, we calculate how many widgets are activated with ‘wp_get_sidebars_widgets()’. Then we called the function calc_span() and we pass along how many widgets are activated in the current widget, which will return the correct span width.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function calc_span($count) { switch($count) { case '1': return '12'; break; case '2': return '6'; break; case '3': return '4'; break; case '4': return '3'; break; case '6': return '2'; break; case '12': return '1'; break; } } |
Depending on which grid system you use, you may need to change the return value. Now when a user adds and removes widgets, the layout will adjust accordingly.
Sorry, the comment form is closed at this time.