钩子文档

widget_text

💡 云策文档标注

概述

widget_text 是一个 WordPress 过滤器钩子,用于过滤文本小部件的内容。它允许开发者在输出前修改小部件文本,适用于 WP_Widget_Text 和 WP_Widget_Custom_HTML 等小部件。

关键要点

  • 过滤器钩子名称为 'widget_text',用于过滤文本小部件的内容。
  • 参数包括 $text(小部件内容字符串)、$instance(当前小部件设置数组)和 $widget(当前小部件实例对象)。
  • 从 WordPress 4.8.1 版本起,$widget 参数可能为 WP_Widget_Custom_HTML 对象,扩展了适用范围。
  • 此钩子也可用于第三方小部件,以替换侧边栏小部件中的任何文本。

代码示例

add_filter('widget_text', 'wpdocs_text_replace');

function wpdocs_text_replace($text, $instance, $that) {
    $search = 'welcome admin';
    $replace = 'welcome adam';
    $text = str_replace($search, $replace, $that);

    return $text;
}

📄 原文内容

Filters the content of the Text widget.

Parameters

$textstring
The widget content.
$instancearray
Array of settings for the current widget.
$widgetWP_Widget_Text|WP_Widget_Custom_HTML
Current text or HTML widget instance.

More Information

May also apply to some third party widgets as well. This filter hook can be used to replace any text within sidebar widgets.

Source

$text = apply_filters( 'widget_text', $text, $instance, $this );

Changelog

Version Description
4.8.1 The $widget param may now be a WP_Widget_Custom_HTML object in addition to a WP_Widget_Text object.
4.4.0 Added the $widget parameter.
2.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    The following performs a string replace on the content of the Text widget.

    add_filter('widget_text', 'wpdocs_text_replace');
    
    function wpdocs_text_replace($text, $instance, $that) {
        $search = 'welcome admin';
        $replace = 'welcome adam';
        $text = str_replace($search, $replace, $that);
    
        return $text;
    }