Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadmohr/227aef3e3823db00d080 to your computer and use it in GitHub Desktop.
Save chadmohr/227aef3e3823db00d080 to your computer and use it in GitHub Desktop.
<?php
/**
* Add "first" and "last" CSS classes to dynamic sidebar widgets. Also adds numeric index class for each widget (widget-1, widget-2, etc.)
*/
function hip_widget_first_last_classes( $params ) {
global $my_widget_num; // Global a counter array
$this_id = $params[0]['id']; // Get the id for the current sidebar we're processing
$arr_registered_widgets = wp_get_sidebars_widgets(); // Get an array of ALL registered widgets
if( !$my_widget_num ) {
// If the counter array doesn't exist, create it
$my_widget_num = array();
}
if( !isset( $arr_registered_widgets[$this_id] ) || !is_array( $arr_registered_widgets[$this_id] ) ) {
// Check if the current sidebar has no widgets
return $params; // No widgets in this sidebar... bail early.
}
if( isset( $my_widget_num[$this_id] ) ) {
// See if the counter array has an entry for this sidebar
$my_widget_num[$this_id] ++;
} else {
// If not, create it starting with 1
$my_widget_num[$this_id] = 1;
}
// Add a widget number class for additional styling options
$class = 'class="widget_' . $my_widget_num[$this_id] . ' ';
if( $my_widget_num[$this_id] == 1 ) {
// If this is the first widget
$class .= 'widget_first ';
} elseif( $my_widget_num[$this_id] == count( $arr_registered_widgets[$this_id] ) ) {
// If this is the last widget
$class .= 'widget_last ';
}
// Insert our new classes into "before widget"
$params[0]['before_widget'] = str_replace( 'class="', $class, $params[0]['before_widget'] );
return $params;
}
add_filter( 'dynamic_sidebar_params', 'hip_widget_first_last_classes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment