wp_pre_kses_block_attributes()
云策文档标注
概述
wp_pre_kses_block_attributes() 是一个 WordPress 函数,用于在文章上下文中过滤时,从解析的块属性值中移除不允许的 HTML。它作为 'pre_kses' 钩子的回调函数,通过临时移除自身过滤器来避免递归调用,并调用 filter_block_content() 进行实际过滤。
关键要点
- 函数作用:在 KSES 过滤前,清理块属性中的非允许 HTML,确保内容安全。
- 参数:$content(字符串,必需)为要过滤的内容;$allowed_html(数组或字符串,必需)指定允许的 HTML 元素和属性或上下文;$allowed_protocols(字符串数组,必需)为允许的 URL 协议。
- 返回值:返回经过过滤的字符串,供 KSES 进一步处理。
- 实现机制:通过 remove_filter() 临时移除自身过滤器,调用 filter_block_content() 执行过滤,然后使用 add_filter() 重新添加过滤器。
- 相关函数:与 filter_block_content()、remove_filter() 和 add_filter() 紧密关联。
- 版本历史:自 WordPress 5.3.1 版本引入。
代码示例
function wp_pre_kses_block_attributes( $content, $allowed_html, $allowed_protocols ) {
remove_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10 );
$content = filter_block_content( $content, $allowed_html, $allowed_protocols );
add_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10, 3 );
return $content;
}
原文内容
Removes non-allowable HTML from parsed block attribute values when filtering in the post context.
Parameters
$contentstringrequired-
Content to be run through KSES.
$allowed_htmlarray[]|stringrequired-
An array of allowed HTML elements and attributes, or a context name such as
'post'. $allowed_protocolsstring[]required-
Array of allowed URL protocols.
Source
function wp_pre_kses_block_attributes( $content, $allowed_html, $allowed_protocols ) {
/*
* `filter_block_content` is expected to call `wp_kses`. Temporarily remove
* the filter to avoid recursion.
*/
remove_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10 );
$content = filter_block_content( $content, $allowed_html, $allowed_protocols );
add_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10, 3 );
return $content;
}
Changelog
| Version | Description |
|---|---|
| 5.3.1 | Introduced. |