X

How to Add Styling Widgets Based on Their Position in a Widget Area

Snippets by IsItWP

Are you looking for a way to create dynamic widgets in WordPress? While there’s probably a plugin for this, we have created a quick code snippet that you can use to add styling widgets based on their position in a widget area in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:


function widget_position_style_dynamic_sidebar_params( $params ) {
	if( is_admin() )
		return $params;

	$widgets = wp_get_sidebars_widgets();
	$area = $params[0]['id'];
	$order = array_search( $params[0]['widget_id'], $widgets[$area] ) + 1;
	$params[0]['before_widget'] = '<div class="widget-'. ordinal( $order ) .'">' . $params[0]['before_widget'];
	$params[0]['after_widget'] .= '</div>';
	return $params;
}
add_filter( 'dynamic_sidebar_params', 'widget_position_style_dynamic_sidebar_params' );

function ordinal( $num ) {
	// Special case "teenth"
	if ( ($num / 10) % 10 != 1 ) {
		// Handle 1st, 2nd, 3rd
		switch( $num % 10 ) {
			case 1: return $num . 'st';
			case 2: return $num . 'nd';
			case 3: return $num . 'rd';
		}
	}
	// Everything else is "nth"
	return $num . 'th';
}

This code will add a wrapper div around your widgets and apply ‘widget-1st’, ‘widget-2nd’ class names to them. Now, you can target that widget in your CSS: #mysidebar .widget-1st { background: red }.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 10 best WordPress plugins for web developers and how to save partial form data in WordPress.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!