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?
Leave a Reply
You must be logged in to post a comment.
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 yourbefore_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.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.Here’s a related discussion on the WordPress.org forum: http://wordpress.org/support/topic/dynamic-widget-classes-for-use-in-css