Add individual <hx> tag to widget title in sidebar

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>.

Read More

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?

Related posts

Leave a Reply

1 comment

  1. 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

    ADDED AN EXAMPLE ON REQUEST

    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]++;
        else
            $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;
    }