钩子文档

widget_block_content

💡 云策文档标注

概述

widget_block_content 是一个 WordPress 过滤器,用于在输出 Block widget 内容之前对其进行修改。它允许开发者动态调整 widget 的内容,例如基于条件进行文本替换或 HTML 修改。

关键要点

  • 这是一个过滤器,应用于 Block widget 的内容输出前。
  • 参数包括 $content(widget 内容字符串)、$instance(当前 widget 的设置数组)和 $widget(当前 Block widget 实例)。
  • 在 WordPress 5.8.0 版本中引入。
  • 常用于内容翻译、HTML 代码调整等场景。

代码示例

function wpdocs_translating_widget( $content ) {
    $locale = get_locale();
    if ( is_home() && $locale !== 'es_ES' ) {
        $replace = array(
            'Entradas recientes' => 'Recent entries',
            'BUSCAR' => 'SEARCH',
        );
        $content = str_replace( array_keys( $replace ), $replace, $content );
    }
    return $content;
}  
add_filter( 'widget_block_content', 'wpdocs_translating_widget' );

📄 原文内容

Filters the content of the Block widget before output.

Parameters

$contentstring
The widget content.
$instancearray
Array of settings for the current widget.
$widgetWP_Widget_Block
Current Block widget instance.

Source

echo apply_filters(
	'widget_block_content',
	$instance['content'],
	$instance,
	$this
);

Changelog

Version Description
5.8.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Really useful if, for example, we want to translate a piece of text (or change HTML code).
    Example:

    function wpdocs_translating_widget( $content ) {
        $locale = get_locale();
        if ( is_home() && $locale !== 'es_ES' ) {
            $replace = array(
                'Entradas recientes' => 'Recent entries',
                'BUSCAR' => 'SEARCH',
            );
            $content = str_replace( array_keys( $replace ), $replace, $content );
        }
        return $content;
    }  
    add_filter( 'widget_block_content', 'wpdocs_translating_widget' );