apply_filters无法替换WordPress默认近期评论小工具文本问题求助
问题原因
你之前的代码失效有两个核心原因:
- 用错了钩子:
widget_text_content仅作用于默认文本小部件,对最近评论小部件输出不生效 - 混淆了函数用法:
apply_filters是触发钩子执行过滤,挂载自定义过滤函数需要用add_filter
可用解决方案
提供两个兼容度高的实现方案,任选其一即可:
方案1:使用最近评论小部件专属输出钩子(推荐)
这个钩子仅作用于最近评论小部件,不会误改站点其他位置的文本,精准度最高:
// 过滤最近评论小部件输出,移除独立的'on'字符串 add_filter('widget_recent_comments_output', 'remove_recent_comments_on_text', 10, 3); function remove_recent_comments_on_text($output, $comments, $instance) { // 替换前后带空格的'on',避免误改其他包含on的英文单词 $output = str_replace(' on ', '', $output); return $output; }
方案2:使用翻译字符串钩子(兼容性最强)
直接拦截你找到的原生翻译字符串,和小部件输出逻辑无关,适配所有WordPress版本:
// 精准过滤最近评论模块的翻译字符串,移除'on' add_filter('gettext_with_context', 'remove_recent_comments_on_translate', 10, 4); function remove_recent_comments_on_translate($translation, $text, $context, $domain) { if ($context === 'widgets' && $text === '%1$s on %2$s') { $translation = '%1$s %2$s'; } return $translation; }
操作步骤
将以上任意一段代码复制到子主题的functions.php文件末尾,保存后清理站点缓存、浏览器缓存即可生效。
内容的提问来源于stack exchange,提问作者igroglaz
相关产品推荐
相关产品推荐

