Take the 2-minute tour ×

In my sidebar every widget title is enclosed in <h2> tags.

I use 4 widgets in my sidebar and I'd like to have the first 2 widget titles as <h2> and the other 2 as <h4>.

I changed in my function.php as given below:

'before_title' => '<h4>', 
'after_title' => '</h4>',

but that changes all titles.
How can I solve this issue?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

dynamic_sidebar_params is the filter that lets you modify those parameters on a per-widget basis. It fires for every sidebar though, so you'll need to use both add_action & remove_action call. Try var_dump once before writing the code to get an idea of what you have to do


This example adds an extra class to each widget depending on the order in which they appear i.e. first widget will have class "widget-1", 2nd will have "widget-2" & so on

function add_first_last_class_to_widget($params) {
    STATIC $widget_num = array();
    $this_id = $params[0]['id'];
    $arr_registered_widgets = wp_get_sidebars_widgets();
    if (!isset($arr_registered_widgets[$this_id]) || !is_array($arr_registered_widgets[$this_id]))
        return $params;

    if (isset($widget_num[$this_id]))
        $widget_num[$this_id] = 1;
    $class = 'class="widget-' . $widget_num[$this_id] . ' ';

    $params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']);

    return $params;
share|improve this answer
I didn't find proper example for this dynamic_sidebar_params. How to use this I don't understand is it possible to give one small example. I'm new in wordpress. –  wasim kazi Oct 23 '12 at 9:17
edited the answer :) –  Mridul Aggarwal Oct 23 '12 at 9:48
Thanks Mridul.. –  wasim kazi Oct 23 '12 at 10:04

Your Answer


