Wordpress : Change title of sidebar widget dynamically

↘锁芯ラ 提交于 2019-12-03 18:11:16

问题


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


回答1:


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');


来源:https://stackoverflow.com/questions/6078112/wordpress-change-title-of-sidebar-widget-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!