【问题标题】:Wordpress: How to apply a widget_title filter only to the widgets from a certain sidebar?Wordpress:如何仅将 widget_title 过滤器应用于某个侧边栏中的小部件?
【发布时间】:2012-12-03 22:39:50
【问题描述】:

我只需要将 widget_title 过滤器应用于某个侧边栏中的小部件。 如果小部件来自“页脚”,我想应用:

function widget_title_empty($output='') {
    if ($output == '') {
        return ' ';
    }
    return $output;
}
add_filter('widget_title', 'widget_title_empty');

给它。

谢谢。

【问题讨论】:

    标签: wordpress filter widget title


    【解决方案1】:

    由于您想使用硬编码的侧边栏名称,我假设您正在创建一个主题并控制打印侧边栏的代码?如果是这样,您可以先添加过滤器,然后再次将其删除,如下所示:

    add_filter('widget_title', 'widget_title_empty');
    dynamic_sidebar('footer');
    remove_filter('widget_title', 'widget_title_empty');
    

    这样,周围的侧边栏不会受到影响。

    【讨论】:

      【解决方案2】:

      如果您只想删除小部件标题,您可以通过将"__return_false" 作为参数传递给过滤器来执行此操作,而无需创建自定义函数:

      add_filter('widget_title', '__return_false');
      dynamic_sidebar('footer');
      remove_filter('widget_title', '__return_false');
      

      http://codex.wordpress.org/Function_Reference/_return_false

      【讨论】:

        【解决方案3】:

        我更喜欢 Calle 的回答,但如果您没有这些条件,这将起作用:

        class Example {
        
            protected $lastWidget = false;
        
            public function __construct() {
                add_filter('dynamic_sidebar_params', array($this, 'filterSidebarParams'));
            }
        
            /**
            * record what sidebar widget is being processed
            * @param array $widgetParams
            * @return array
            */
            public function filterSidebarParams($widgetParams) {
                $this->lastWidget = $widgetParams;
        
                return $widgetParams;
            }
        
            /**
            * check to see if last widget recorded was in sidebar
            * @param string $sidebarName
            * @return bool
            */
            public function isLastSidebar($sidebarName) {
                return $this->lastWidget && $this->lastWidget[0]['id'] == $sidebarName;
            }
        
        }
        
        $example = new Example();
        
        // in your widget's code
        if ($example->isLastSidebar('footer-widget-area')) {
            // you're in
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-12
          • 2012-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多