render_block_{$this->name}
云策文档标注
概述
render_block_{$this->name} 是一个用于过滤单个块内容的动态 Hook。它允许开发者在块渲染过程中修改块内容,基于块名称进行定制化处理。
关键要点
- Hook 名称是动态的,$name 对应块名称,例如 "core/paragraph"。
- 参数包括 $block_content(块内容字符串)、$block(完整块数组)和 $instance(WP_Block 实例)。
- 在 WordPress 5.9.0 中新增了 $instance 参数,5.7.0 版本引入此 Hook。
- 与 WP_Block::render() 方法关联,用于生成块的渲染输出。
- 使用时需注意优先级设置,例如对于图像块的 Expand on Click 功能,建议优先级至少为 16 以访问 lightbox 标记。
代码示例
add_filter( 'render_block_core/navigation', 'wpdocs_modify_nav_menu_for_admins', 10, 2 );
function wpdocs_modify_nav_menu_for_admins( $block_content, $block ) {
if ( isset( $block['blockName'] ) && 'core/navigation' === $block['blockName'] ) {
if ( is_user_logged_in() && current_user_can( 'administrator' ) ) {
$custom_message = 'Welcome, Admin!';
$block_content = $custom_message . $block_content;
}
}
return $block_content;
}注意事项
- $block 数组包含 blockName、attrs、innerBlocks、innerHTML 和 innerContent 等键,具体可参考 WP_Block 类文档。
- 对于图像块,如果需处理 Expand on Click 的 lightbox 标记,应设置过滤器优先级至少为 16,以避免内置过滤器的影响。
原文内容
Filters the content of a single block.
Description
The dynamic portion of the hook name, $name, refers to the block name, e.g. “core/paragraph”.
Parameters
$block_contentstring-
The block content.
$blockarray-
The full block, including name and attributes.
$instanceWP_Block-
The block instance.
Source
$block_content = apply_filters( "render_block_{$this->name}", $block_content, $this->parsed_block, $this );
Skip to note 4 content
Artemio Morales
If you’ve arrived here wondering why your image block with
Expand on Clickenabled contains lightbox markup that you seemingly can’t access from inside your filter function, here’s some extra information you might need:As of WordPress 6.4, please be aware that a built-in filter for the image block has been applied with priority 15 for images with
Expand on Click. This means that if your filter has a priority of 15 or lower (the default is 10), then the markup used to create the lightbox behavior will NOT be available to your function for processing by default.Please make sure to use priority of at least 16 when adding filters to process the image block if you need to access the lightbox markup:
add_filter( 'render_block_core/image', 'wpdocs_custom_html', 16 )See this issue for more details.
Skip to note 5 content
Lovro Hrust
$blockis array with keys:These keys are explained and referenced in WP_Block
Skip to note 6 content
WP SITES
Filter the core navigation block conditionally. Prepends content to the core navigation block.
add_filter( 'render_block_core/navigation', 'wpdocs_modify_nav_menu_for_admins', 10, 2 ); function wpdocs_modify_nav_menu_for_admins( $block_content, $block ) { if ( isset( $block['blockName'] ) && 'core/navigation' === $block['blockName'] ) { if ( is_user_logged_in() && current_user_can( 'administrator' ) ) { $custom_message = 'Welcome, Admin!'; $block_content = $custom_message . $block_content; } } return $block_content; }