How Do I Add Custom CSS To Only Certain Widgets

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

<?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;
}

Leave a Comment