Question

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?

Was it helpful?

Solution

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):

<?php
add_filter('dynamic_sidebar_params','my_dynamic_sidebar_params');
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;
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top