Add class to last widget in widget area

Im using the the following PHP to display a number of widgets in my WordPress theme:

<?php
// A sidebar for widgets, just because.
if ( is_active_sidebar( 'primary-widget-area' ) ) : ?>
    <ul>
        <?php dynamic_sidebar( 'primary-widget-area' ); ?>
    </ul>
<?php endif; ?>

Basically each widget in the <ul> comes out as a list item. I want to be able to add a class to the last list item in the list.

Read More

Is it possible for me to do this with wordpress/php?

Related posts

Leave a Reply

3 comments

  1. If you want to add a custom class for first or last widget inner sidebar.

    You can using action hook “init”

    • get all activate widgets, sidebars
    • loop through each widget and change the class names
    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'] .= ' ct-widget-order-' . $i;
    
                # Add first widget class
                if ( 0 == $i ) {
                    $wp_registered_widgets[$widget_id]['classname'] .= ' ct-widget-first';
                }
    
                # Add last widget class
                if ( $number_of_widgets == ( $i + 1 ) ) {
                    $wp_registered_widgets[$widget_id]['classname'] .= ' ct-widget-last';
                }
            }
        }
    }
    

    my blog: http://colourstheme.com/2015/03/add-class-to-first-and-last-widget/