Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need to apply a certain style to every second widget in my sidebar, and I'm reluctant to use :nth-child due to cross-browser compatibility issues. Is there a bit of PHP that will allow me to apply a class to every other widget?

share|improve this question
add comment

3 Answers 3

up vote 4 down vote accepted

Use the dynamic_sidebar_params filter. The following code adds classes to say whether the widget is odd or even, what index it is in the sidebar, and what sidebar it's in.

Note: the str_replace("class=\"", "class=\"$class ", $before_widget); code below depends on your before_widget using double quotes -- it probably should be done with a regular expression to handle single quotes as well. I just haven't ever got around to it.

function my_filter_dynamic_sidebar_params($params){

    static $sidebar_widget_count = array();
    $sidebar_id = $params[0]["id"];
    if (! isset($sidebar_widget_count[$sidebar_id])){
        $sidebar_widget_count[$sidebar_id] = 0;
    }
    $before_widget = $params[0]['before_widget'];
    $class = $sidebar_widget_count[$sidebar_id] % 2 ? 
        "widget-odd" : "widget-even";
    $class .= " widget-index-" . $sidebar_widget_count[$sidebar_id];
    $class .= " widget-in-$sidebar_id";
    $before_widget = str_replace("class=\"", 
        "class=\"$class ", $before_widget);
    $params[0]['before_widget'] = $before_widget;
    $sidebar_widget_count[$sidebar_id]++;
    return $params;
}

add_filter("dynamic_sidebar_params", "my_filter_dynamic_sidebar_params");
share|improve this answer
    
How could this code be updated to include a class for the total number of widgets? For example widget-count-3 –  Mr Jonny Wood Jun 27 '12 at 14:13
add comment

Here's a related discussion on the WordPress.org forum: http://wordpress.org/support/topic/dynamic-widget-classes-for-use-in-css

share|improve this answer
add comment

This would probably be a great place to make use of the CSS :nth-child pseudo-class, especially :nth-child(odd) and :nth-child(even). I wouldn't worry too much about browser compatibility. If you must, just use jQuery for IE8.

share|improve this answer
add comment

Your Answer

 
discard

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.