Support » Fixing WordPress » alternating classes with widgets

  • I originally posted the following question in Themes and Templates, but was suggested to post here instead.

    I am in the process of developing (my first custom theme) for a client. One of the things I need to be able to do is to have the class surrounding a widget alternate dyanamically so that if there are 2 widgets the first one would have <div class=”widget1″> and the second would be <div class=”widget2″>

    Then the next widget would go back to the first class and repeat – preferably 3 classes switching would be great, but 2 will work.

    Can this be done and if so how?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The dynamic_sidebar routine in WP (i’m looking at the 2.7 code) sets up a $params array and then filters it like this

    $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_);
    $params = apply_filters( 'dynamic_sidebar_params', $params );

    so you can step in there by using an add_filter

    to change the [0][‘before_widget’] using a str_replace or however you prefer. the before_widget parameter is the string to print before the heading of the widget. it’s usually a DIV or a LI that contains a class=”widget widget_name” string

    Thank you, will attempt this tomorrow.


    Sorry for the late reply.

    I don’t understand how to use the code and link you provided. In my functions.php file I’ve got the following.

    if ( function_exists('register_sidebar') )
        register_sidebars(2, array(
            'before_widget' => '<div class="widget1">',
            'after_widget' => '</div><!--widget1-->',
            'before_title' => '<h3 class="shortsifr">',
            'after_title' => '</h3>',

    What do I do with the code you provided.

    Thank you for your help.

    sounds like you may not be familiar with writing filters. you should read that codex page i linked to first. what you need is:

    add_filter('dynamic_sidebar_params',  'my_dynamic_sidebar_params_filter');
    function my_dynamic_sidebar_params_filter($params)
    	[code to alter $params]
    	return $params;

    what that is doing is registering your own routine with the core WP code to be called whenever it runs $params=apply_filters( 'dynamic_sidebar_params', $params );

    so your routine can step in and alter $params. and as this filter is called every time a widget is about to be called, you can tinker with the before_widget for each widget.

    hope this has pointed you in the right direction, and let us know how you get on.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘alternating classes with widgets’ is closed to new replies.