WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 6 down vote accepted

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;
share|improve this answer
Great snippet! Thanks a lot! – John P Bloch Aug 19 '10 at 13:25

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.

share|improve this answer

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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