Wordpress

Add class to first and last widget

By 1 Comment

If you want to Add class to first and last widget inner sidebar. Please read my guide to do it.

You can using action hook “init”

  • get all activate widgets, sidebars
  • loop through each widget and change the class names

Note: to apply this tutorial, you must register sidebar with valid syntax http://codex.wordpress.org/Function_Reference/register_sidebar


add_action('init', 'ak_add_order_classes_for_widgets' );
 
function ak_add_order_classes_for_widgets() {
    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'] .= ' ak-widget-order-' . $i;
 
            # Add first widget class
            if ( 0 == $i ) {
                $wp_registered_widgets[$widget_id]['classname'] .= ' ak-widget-first';
            }
 
            # Add last widget class
            if ( $number_of_widgets == ( $i + 1 ) ) {
                $wp_registered_widgets[$widget_id]['classname'] .= ' ak-widget-last';
            }
        }
    }
}