Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress : Change title of sidebar widget dynamically

Tags:

wordpress

Is it possible to get the title of the widgets that I have enabled in my sidebar so I can insert that as a name for my class attribute?

For example: 'before_title' => <h2 class="title of the widget">',

If I inspect the element, I want to see: <h2 class="author"> and <h2 class="links"> etc...

Thanks

like image 283
rabid_zombie Avatar asked Jan 19 '23 16:01

rabid_zombie


1 Answers

It's definitely possible, but if you want to do it dynamically, you'd need to use a filter.

The dynamic_sidebar_params filter should work for you. If you're unfamiliar with what filters do, basically a filter allows you to edit content before it's displayed on screen or saved in the database. See more here: http://codex.wordpress.org/Plugin_API/Filter_Reference

In the dynamic_sidebar_params filter, the passed array has the following structure (I got this from doing a print_r)

Array
(
    [0] => Array
        (
            [name] => Primary Widget Area
            [id] => primary-widget-area
            [description] => The primary widget area
            [before_widget] => <li id="search-2" class="widget-container widget_search">
            [after_widget] => </li>
            [before_title] => <h3 class="widget-title">
            [after_title] => </h3>
            [widget_id] => search-2
            [widget_name] => Search
        )

    [1] => Array
        (
            [number] => 2
        )

)

So that means, all you have to do is edit the $params array before returning it. You might have to do some conditional logic as well to get the exact class that you want, but I'll leave that up to you.

Here is an example:

function my_edit_widget_func($params) {
    $params[0]['before_title'] = '<h3 class="' . $params[0]['widget_name'] . '">' ;
    return $params;
}
add_filter('dynamic_sidebar_params', 'my_edit_widget_func');
like image 59
Philip Walton Avatar answered Jan 29 '23 13:01

Philip Walton