函数文档

do_blocks()

💡 云策文档标注

概述

do_blocks() 函数用于解析 post_content 中的动态块并重新渲染它们,更新内容字符串。它通过 parse_blocks() 解析块,然后逐个渲染以优化内存使用。

关键要点

  • 函数参数:$content(字符串,必需),表示要解析的帖子内容。
  • 返回值:字符串,返回更新后的帖子内容。
  • 内部实现:使用 parse_blocks() 解析内容为块数组,然后循环调用 render_block() 渲染每个顶级块,并在渲染后设置块为 NULL 以释放内存,避免内存溢出。
  • 相关函数:parse_blocks()、render_block()、has_blocks() 等,用于块解析和渲染。
  • 引入版本:WordPress 5.0.0。

代码示例

echo do_blocks( '<!-- wp:site-logo /-->' );

注意事项

  • 函数类似于 do_shortcode(),用于处理块内容。
  • 在代码示例中,确保使用正确的引号(如单引号)包裹块内容,以避免语法错误。

📄 原文内容

Parses dynamic blocks out of post_content and re-renders them.

Parameters

$contentstringrequired
Post content.

Return

string Updated post content.

Source

function do_blocks( $content ) {
	$blocks                = parse_blocks( $content );
	$top_level_block_count = count( $blocks );
	$output                = '';

	/**
	 * Parsed blocks consist of a list of top-level blocks. Those top-level
	 * blocks may themselves contain nested inner blocks. However, every
	 * top-level block is rendered independently, meaning there are no data
	 * dependencies between them.
	 *
	 * Ideally, therefore, the parser would only need to parse one complete
	 * top-level block at a time, render it, and move on. Unfortunately, this
	 * is not possible with <a href="https://developer.wordpress.org/reference/functions/parse_blocks/">parse_blocks()</a> because it must parse the
	 * entire given document at once.
	 *
	 * While the current implementation prevents this optimization, it’s still
	 * possible to reduce the peak memory use when calls to `render_block()`
	 * on those top-level blocks are memory-heavy (which many of them are).
	 * By setting each parsed block to `NULL` after rendering it, any memory
	 * allocated during the render will be freed and reused for the next block.
	 * Before making this change, that memory was retained and would lead to
	 * out-of-memory crashes for certain posts that now run with this change.
	 */
	for ( $i = 0; $i < $top_level_block_count; $i++ ) {
		$output      .= render_block( $blocks[ $i ] );
		$blocks[ $i ] = null;
	}

	// If there are blocks in this content, we shouldn't run wpautop() on it later.
	$priority = has_filter( 'the_content', 'wpautop' );
	if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
		remove_filter( 'the_content', 'wpautop', $priority );
		add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
	}

	return $output;
}

Changelog

Version Description
5.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can see this function as an equivalent of do_shortcode. For example, it’s possible to render the Site Logo block that way:

    echo do_blocks( <!-- wp:site-logo /--> );