Add .first & .last CSS Class Automatically To WordPress Widgets

Previously we showed you how to Add .first & .last CSS class to WordPress Navigation Menus to help with styling attributes when designing a WordPress theme. Today I though it would be beneficial to follow up that tutorial with one that shows you how to automatically add .first & .last CSS class’s to all WordPress widgets displayed anywhere on your site by adding a simple filter to the wordpress dynamic_sidebar_params function.

Step 1: Adding The Widgets Modification WordPress Filter

Firstly you will want to open your current themes functions.php file then copy the codeblack below and paste it into your functions.php file at the bottom, close and save your functions.php file.

//----------------------- [ Widget .first & .last CSS Classes ] ----------------------//

/**
 * Add "first" and "last" CSS classes to dynamic sidebar widgets. Also adds numeric index class for each widget (widget-1, widget-2, etc.)
 */
function 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;
	}

	$class = 'class="widget-' . $my_widget_num[$this_id] . ' '; // Add a widget number class for additional styling options

	if($my_widget_num[$this_id] == 1) { // If this is the first widget
		$class .= 'first-widget ';
	} elseif($my_widget_num[$this_id] == count($arr_registered_widgets[$this_id])) { // If this is the last widget
		$class .= 'last-widget ';
	}

	$params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']); // Insert our new classes into "before widget"

	return $params;

}
add_filter('dynamic_sidebar_params','widget_first_last_classes');

The code above will now automatically add the CSS class .first-widget to your widget areas first widget and also add the CSS class .last-widget to your widget areas last widget.

You can now easily style and use those css properties in your WordPress themes stylesheet, this is a technique I tend to use in all my themes for easy styling just in case it’s required during development.

As always any opinions or improvments please leave a comment.