I have a standard dynamic sidebar using register_sidebar and dynamic_sidebar and I need the last widget in the sidebar (which will not have a set number of widgets) to have a distinct class ('last_widget') added to the <li> that wraps it. What's the best way to do this?

3 Answers 3


Hi John:

I think this is what you are looking for (I'd explain the code be I think it's self-explanatory; let me know if not):

function my_dynamic_sidebar_params($params) {
    $sidebar_id = $params[0]['id'];
    $sidebar_widgets = wp_get_sidebars_widgets();
    $last_widget_id = end($sidebar_widgets[$sidebar_id]);
    if ($last_widget_id==$params[0]['widget_id'])
        $params[0]['before_widget'] = str_replace(' class="',' class="last_widget ',$params[0]['before_widget']);
    return $params;

You could also use CSS to select the last widget using :last-child (although IE would not like this), or use jQuery to select it. But the PHP code above is probably the better way to do it.


I wrote a patch that does this for core code, the related ticket is #12615 - Add "first" and "last" CSS-class-names to each Widget in sidebars (Frontend)

The patch is a working solution, there are some widget internals that make using end() on the sidebar array as mike suggests it with his code not properly working (Yeah, that would have been too simple, right :P ).

Let me know if the patch does not apply clean any longer. I have this running very well on 2.9.2 sites.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.