函数文档

filter_block_content()

💡 云策文档标注

概述

filter_block_content() 函数用于过滤和清理块内容,移除解析后的块属性值中不允许的 HTML。它通过解析块、应用 wp_kses 规则并序列化块来实现安全处理。

关键要点

  • 函数接受文本参数 $text(必需),可能包含块内容。
  • 可选参数 $allowed_html 指定允许的 HTML 元素和属性,默认为 'post' 上下文。
  • 可选参数 $allowed_protocols 指定允许的 URL 协议,默认为 wp_allowed_protocols() 的结果。
  • 返回过滤和清理后的内容字符串。
  • 内部使用 parse_blocks()、filter_block_kses() 和 serialize_block() 函数处理块。
  • 自 WordPress 5.3.1 版本引入。

代码示例

function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
    $result = '';

    if ( str_contains( $text, '' ) ) {
        $text = preg_replace_callback( '%%', '_filter_block_content_callback', $text );
    }

    $blocks = parse_blocks( $text );
    foreach ( $blocks as $block ) {
        $block   = filter_block_kses( $block, $allowed_html, $allowed_protocols );
        $result .= serialize_block( $block );
    }

    return $result;
}

注意事项

  • 函数主要用于块编辑器(Gutenberg)环境,确保块内容的安全性。
  • 相关函数包括 filter_block_kses()、serialize_block() 和 parse_blocks(),用于块处理的不同阶段。
  • 被 wp_pre_kses_block_attributes() 函数调用,在文章上下文中过滤块属性。

📄 原文内容

Filters and sanitizes block content to remove non-allowable HTML from parsed block attribute values.

Parameters

$textstringrequired
Text that may contain block content.
$allowed_htmlarray[]|stringoptional
An array of allowed HTML elements and attributes, or a context name such as 'post'. See wp_kses_allowed_html() for the list of accepted context names. Default 'post'.
$allowed_protocolsstring[]optional
Array of allowed URL protocols.
Defaults to the result of wp_allowed_protocols() .

Default:array()

Return

string The filtered and sanitized content result.

Source

function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
	$result = '';

	if ( str_contains( $text, '<!--' ) && str_contains( $text, '--->' ) ) {
		$text = preg_replace_callback( '%<!--(.*?)--->%', '_filter_block_content_callback', $text );
	}

	$blocks = parse_blocks( $text );
	foreach ( $blocks as $block ) {
		$block   = filter_block_kses( $block, $allowed_html, $allowed_protocols );
		$result .= serialize_block( $block );
	}

	return $result;
}

Changelog

Version Description
5.3.1 Introduced.