钩子文档

pre_render_block

💡 云策文档标注

概述

pre_render_block 是一个 WordPress 过滤器钩子,允许在 render_block() 函数执行前中断渲染过程,通过返回非空值来直接提供预渲染内容。

关键要点

  • 钩子名称:pre_render_block
  • 作用:允许开发者通过返回非空值来短路 render_block() 的渲染流程,直接输出预渲染内容
  • 参数:$pre_render(预渲染内容,默认 null)、$parsed_block(解析后的块数组)、$parent_block(父块引用,可选)
  • 应用场景:常用于自定义块渲染、性能优化或动态内容生成
  • 版本历史:WordPress 5.1.0 引入,5.9.0 添加 $parent_block 参数

代码示例

$pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );

注意事项

  • 返回非空值(如字符串)将跳过默认渲染,直接使用该值作为输出
  • $parsed_block 包含块的结构化数据,如 blockName、attrs、innerBlocks 等
  • 在嵌套块中,$parent_block 提供对父块的引用,可用于上下文相关渲染

📄 原文内容

Allows render_block() to be short-circuited, by returning a non-null value.

Parameters

$pre_renderstring|null
The pre-rendered content. Default null.
$parsed_blockarray
An associative array of the block being rendered. See WP_Block_Parser_Block.

  • blockName string|null
    Name of block.
  • attrs array
    Attributes from block comment delimiters.
  • innerBlocks array[]
    List of inner blocks. An array of arrays that have the same structure as this one.
  • innerHTML string
    HTML from inside block comment delimiters.
  • innerContent array
    List of string fragments and null markers where inner blocks were found.

$parent_blockWP_Block|null
If this is a nested block, a reference to the parent block.

Source

$pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );

Changelog

Version Description
5.9.0 The $parent_block parameter was added.
5.1.0 Introduced.