【问题标题】: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');
这样,周围的侧边栏不会受到影响。
【解决方案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
}