First and last widget classes
Published June 18th, 2012 under General
Here is a simple filter to automatically add a class attribute like widget-order-1 to all widgets within sidebars:
My colleague Kaspars Dambis published a blog post recently outlining a cunning way to “add a class attribute like widget-order-1 to all widgets within” widget areas in WordPress. This works very well and allows you to target specific widgets with different styling (eg: the first, second, third widgets etc). This is an extremely handy feature when you are attempting to style widget areas within WordPress.
I’ve added an extra feature to Kaspars code, by adding support for “.first-widget” and “.last-widget” classes, so that you know which widget is at the very start and ends of your widget areas. This can be useful for situations in which the last widget needs to look slightly different from the rest, eg: if it should not have a separator line below it.
If you can see any ways to improve this code, please let me know!
<?php /** * Adds order class to widgets * Useful for targetting individual widgets * * Works by modifying the global array containing the sidebar class names * Code adapted from http://konstruktors.com/blog/wordpress/3615-add-widget-order-css-class-sidebar/ * * @since 1.0 * @global array $wp_registered_sidebars List of registered widget areas * @global array $wp_registered_widgets List of registered widgets * @author Ryan Hellyer <ryanhellyer@gmail.com> and Kaspars Dambis <kaspars@metronet.no> and */ function slug_widget_order_class() { global $wp_registered_sidebars, $wp_registered_widgets; // Grab the widgets $sidebars = wp_get_sidebars_widgets(); if ( empty( $sidebars ) ) { return; } // Loop through each widget and change the class names foreach ( $sidebars as $sidebar_id => $widgets ) { if ( empty( $widgets ) ) { continue; } $number_of_widgets = count( $widgets ); foreach ( $widgets as $i => $widget_id ) { $wp_registered_widgets[$widget_id]['classname'] .= ' widget-order-' . $i; // Add first widget class if ( 0 == $i ) { $wp_registered_widgets[$widget_id]['classname'] .= ' first'; } // Add last widget class if ( $number_of_widgets == ( $i + 1 ) ) { $wp_registered_widgets[$widget_id]['classname'] .= ' last'; } } } } add_action( 'init', 'slug_widget_order_class' );
Paul Quinn says:
hello,
great little bit of code, just to help anyone that comes across this, when registering a sidebar, the code above will ignore if you register your sidebar with a classname:
‘before_widget’ => ”,
‘after_widget’ => ”,
So just miss that out and this is super duper function to use.
Thanks
Paul Q
December 17, 2013 at 10:16 am # //