Advertisement
alchymyth

widget classes

Feb 11th, 2013
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.79 KB | None | 0 0
  1. /**
  2.  * Add extra "widget-" CSS class to dynamic sidebar widgets. Also adds numeric index class for each widget (widget-1, widget-2, etc.)
  3. based on http://wordpress.org/support/topic/how-to-first-and-last-css-classes-for-sidebar-widgets?replies=9#post-1726957
  4.  */
  5. function widget_first_last_classes($params) {
  6.  
  7.     global $my_widget_num; // Global a counter array
  8.     $this_id = $params[0]['id']; // Get the id for the current sidebar we're processing
  9.     $arr_registered_widgets = wp_get_sidebars_widgets(); // Get an array of ALL registered widgets 
  10.  
  11.     if(!$my_widget_num) {// If the counter array doesn't exist, create it
  12.         $my_widget_num = array();
  13.     }
  14.  
  15.     if(!isset($arr_registered_widgets[$this_id]) || !is_array($arr_registered_widgets[$this_id])) { // Check if the current sidebar has no widgets
  16.         return $params; // No widgets in this sidebar... bail early.
  17.     }
  18.  
  19.     if(isset($my_widget_num[$this_id])) { // See if the counter array has an entry for this sidebar
  20.         $my_widget_num[$this_id] ++;
  21.     } else { // If not, create it starting with 1
  22.         $my_widget_num[$this_id] = 1;
  23.     }
  24.  
  25.     $class = 'class="widgets-count-' . count($arr_registered_widgets[$this_id]) . ' '; // Add widget count class for additional styling options
  26.     $class .= 'widget-' . $my_widget_num[$this_id] . ' '; // Add a widget number class for additional styling options
  27.    
  28.     if($my_widget_num[$this_id] == 1) { // If this is the first widget
  29.         $class .= 'widget-first ';
  30.     } elseif($my_widget_num[$this_id] == count($arr_registered_widgets[$this_id])) { // If this is the last widget
  31.         $class .= 'widget-last ';
  32.     }
  33.  
  34.     $params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']); // Insert our new classes into "before widget"
  35.  
  36.     return $params;
  37.  
  38. }
  39. add_filter('dynamic_sidebar_params','widget_first_last_classes');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement