函数文档

parse_blocks()

💡 云策文档标注

概述

parse_blocks() 函数用于解析内容字符串中的块,生成块树结构数组。它适用于处理 WordPress 块编辑器内容,但可能消耗较多内存,建议在需要完整解析时使用。

关键要点

  • 解析 HTML 文档中的块内容,返回块结构数组,包括块名、属性、内部块等。
  • 内存消耗较高,特别是对于深度嵌套或属性丰富的块,需一次性解析整个文档。
  • 可替代方案:WP_Block_Processor 提供流式、低开销接口,适合部分解析需求。
  • 支持通过 block_parser_class 过滤器替换服务器端块解析器。
  • 返回数组包含 blockName、attrs、innerBlocks、innerHTML 和 innerContent 等键。

代码示例

// 示例:解析文章内容并查找特定块(如 YouTube 嵌入块)
$blocks = parse_blocks( $post->post_content );
foreach ( $blocks as $block ) {
    if ( 'core-embed/youtube' === $block['blockName'] ) {
        echo apply_filters( 'the_content', render_block( $block ) );
        break;
    }
}

注意事项

  • 自 WordPress 5.6 起,嵌入块名已更改为 core/embed,示例需更新。
  • 检查内容是否为块编辑器内容时,推荐使用 has_blocks() 函数而非 parse_blocks(),以降低开销。
  • 解析后的块数组可配合 serialize_blocks() 转换回内容字符串。

📄 原文内容

Parses blocks out of a content string.

Description

Given an HTML document, this function fully-parses block content, producing a tree of blocks and their contents, as well as top-level non-block content, which will appear as a block with no blockName.

This function can be memory heavy for certain documents, particularly those with deeply-nested blocks or blocks with extensive attribute values. Further, this function must parse an entire document in one atomic operation.

If the entire parsed document is not necessary, consider using WP_Block_Processor instead, as it provides a streaming and low-overhead interface for finding blocks.

Parameters

$contentstringrequired
Post content.

Return

array[] Array of block structures.

  • ...$0 array
    An associative array of a single parsed block object. 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.

Source

function parse_blocks( $content ) {
	/**
	 * Filter to allow plugins to replace the server-side block parser.
	 *
	 * @since 5.0.0
	 *
	 * @param string $parser_class Name of block parser class.
	 */
	$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );

	$parser = new $parser_class();
	return $parser->parse( $content );
}

Hooks

apply_filters( ‘block_parser_class’, string $parser_class )

Filter to allow plugins to replace the server-side block parser.

Changelog

Version Description
5.0.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content

    Example using parse_blocks() to display a block from a post

    post_content );
    	
    	foreach ( $blocks as $block ) {
    
    		// YouTube's block name
    		if ( 'core-embed/youtube' === $block['blockName'] ) {
    			
    			echo apply_filters( 'the_content', render_block( $block ) );
    			
    			break;
    			
    		}
    		
    	}
    	
    }
    
    ?>

    Place within The Loop

    If used in The Loop it renders the first YouTube video embedded within a post. Can be used with other blocks by assigning their blockName.

  2. Skip to note 8 content

    Example of returned array for a Paragraph block:

    array ( 
    	0 => array ( 
    		'blockName' => 'core/paragraph', 
    		'attrs' => array ( 
    			'textColor' => 'vivid-red', 
    			'backgroundColor' => 'luminous-vivid-amber',
    		), 
    		'innerBlocks' => array (
    			/* Child blocks if they exists (used in Column Block for example) */
    		), 
    		'innerHTML' => 'This is a block content!', 
    		'innerContent' => array (
    			0 => 'This is a block content!',
    		), 
    	),
    )

  3. Skip to note 9 content

    As of Gutenberg 7.7, for this input:

    <!-- wp:paragraph {
        "placeholder":"Summary",
        "textColor":"accent",
        "backgroundColor":"secondary"
    } -->
    <p class="has-text-color has-background has-accent-color has-secondary-background-color">
    This is a new paragraph.
    </p>
    <!-- /wp:paragraph -->

    the output of parse_blocks will be:

    Array
    (
      [0] => Array
        (
          [blockName] => core/paragraph
          [attrs] => Array
            (
              [placeholder] => Summary
              [textColor] => accent
              [backgroundColor] => secondary
            )
          [innerBlocks] => Array()
          [innerHTML] => <p class="has-text-color has-background has-accent-color has-secondary-background-color">This is a new paragraph.</p>
          [innerContent] => Array
            (
              [0] => <p class="has-text-color has-background has-accent-color has-secondary-background-color">This is a new paragraph.</p>
            )
          )
    )

  4. Skip to note 10 content

    In case you wish to check if current post content is Gutenberg-blocks or using Classic editor:

        global $post;
        $blocks = parse_blocks( $post->post_content );
        $is_gutenberg_page = ( ! empty( $blocks ) && '' !== $blocks[0]['blockName'] );

    If post content is Classic Editor, it has only one block, but blockName is empty.

You must log in before being able to contribute a note or feedback.