Add the Order of Widgets Within a Sidebar as a CSS Class to All Widgets

Here is a simple filter to automatically add a class attribute like widget-order-1 to all widgets within sidebars:

add_action('init', 'add_widget_order_class');

function add_widget_order_class() {
	global $wp_registered_sidebars, $wp_registered_widgets;

	$sidebars = wp_get_sidebars_widgets();
	if (empty($sidebars))
		return;

	foreach ($sidebars as $sidebar_id => $widgets) {
		if (empty($widgets))
			continue;
		foreach ($widgets as $i => $widget_id) {
			$order = $i + 1;
			$wp_registered_widgets[$widget_id]['classname'] .= ' widget-order-' . $order; 
		}
	}
}

Leave a Reply