How can I add an incremental class identifier to my sidebar widgets?

My sidebar widget code in functions.php looks like this…

if ( function_exists('register_sidebar') )
register_sidebar(array(
    'name' => 'Home Sidebar',
    'id' => 'home-sidebar-widget',
    'before_widget' => '<div class="menu side %2$s">',
    'after_widget' => '</div>',
    'before_title' => '<h4 class="sidebarTitle">',
    'after_title' => '</h4>',
));

Which creates this markup on the site…

Read More
<div class="menu side widget_text">
    <h4>widget 1 title</h4>
    <div class="textwidget">Lorem ipsum dolor sit amet</div>
</div>

<div class="menu side widget_text">
    <h4>widget 2 title</h4>
    <div class="textwidget">Lorem ipsum dolor sit amet</div>
</div>

Here’s what I need (just adding a number to the class collection)…

<div class="menu side s1 widget_text">
    <h4>widget 1 title</h4>
    <div class="textwidget">Lorem ipsum dolor sit amet</div>
</div>

<div class="menu side s2 widget_text">
    <h4>widget 2 title</h4>
    <div class="textwidget">Lorem ipsum dolor sit amet</div>
</div>

I would like to add a count variable so that each sidebar gets a number that I can then use for css targeting. How?

Related posts

Leave a Reply

2 comments

  1. There doesn’t seem to be an easy way to do this. However, you can try this rather hackish approach:

    add_filter('dynamic_sidebar_params', 'my_sidebar_params_cb');
    
    function my_sidebar_params_cb($params) {
        global $my_widget_counter;
        if (empty($my_widget_counter)) $my_widget_counter = 1;
        else $my_widget_counter++;
        $params[0]['before_widget'] = str_replace('class="', 'class="widget_nr_'.$my_widget_counter.' ', $params[0]['before_widget']);
        return $params;
    }
    
  2. You could target specific elements in CSS like so..(won’t work for all browsers of course).

    #sidebar div.menu.side:nth-child(1) { /* First */ }
    #sidebar div.menu.side:nth-child(2) { /* Second */ }
    #sidebar div.menu.side:nth-child(3) { /* Third */ }
    
    ..and so on...
    

    Or use some jQuery to add the classes..

    jQuery(document).ready( function($) {
        var wi = 1;
        $('#sidebar div.menu.side').each( function() {
            $(this).addClass( 'widget-s' + wi );
            wi = wi + 1;
        });
    });
    

    wyrfel’s approach looks like it could work for you though, i’d suggest that over the two above.