函数文档

serialize_block()

💡 云策文档标注

概述

serialize_block() 函数用于序列化解析后的块对象,生成包含注释分隔符和属性的块内容字符串,适用于将块保存到文章内容中。

关键要点

  • 函数返回块内容字符串,包括注释分隔符和序列化属性,用于保存块到文章内容,而非显示渲染。
  • 与 render_block() 不同,serialize_block() 不执行块的 render_callback,保留解析时的原始标记。
  • 参数 $block 为必需,是一个关联数组,表示单个解析块对象,遵循 WP_Block_Parser_Block 结构。
  • 函数递归处理 innerContent 和 innerBlocks,使用 get_comment_delimited_block_content() 生成最终输出。

代码示例

/*
 * Create a block programmatically and serialize it.
 */
$block_name = 'core/paragraph';
$innerHTML  = 'Sample paragraph text.';

$converted_block = new WP_Block_Parser_Block( $block_name, array(), array(), $innerHTML, array( $innerHTML ) );
WP_CLI::log( print_r( $converted_block, true ) );

$serialized_block = serialize_block( (array) $converted_block );
WP_CLI::log( $serialized_block );

📄 原文内容

Returns the content of a block, including comment delimiters, serializing all attributes from the given parsed block.

Description

This should be used when preparing a block to be saved to post content.
Prefer render_block when preparing a block for display. Unlike render_block, this does not evaluate a block’s render_callback, and will instead preserve the markup as parsed.

Parameters

$blockarrayrequired
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.

Return

string String of rendered HTML.

Source

function serialize_block( $block ) {
	$block_content = '';

	$index = 0;
	foreach ( $block['innerContent'] as $chunk ) {
		$block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
	}

	if ( ! is_array( $block['attrs'] ) ) {
		$block['attrs'] = array();
	}

	return get_comment_delimited_block_content(
		$block['blockName'],
		$block['attrs'],
		$block_content
	);
}

Changelog

Version Description
5.3.1 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    A sample code to understand how this works. I am using https://developer.wordpress.org/cli/commands/eval-file/ to execute this.

    /*
     * Create a block programmatically and serialize it.
     */
    $block_name = 'core/paragraph';
    $innerHTML  = 'Sample paragraph text.';
    
    $converted_block = new WP_Block_Parser_Block( $block_name, array(), array(), $innerHTML, array( $innerHTML ) );
    WP_CLI::log( print_r( $converted_block, true ) );
    
    $serialized_block = serialize_block( (array) $converted_block );
    WP_CLI::log( $serialized_block );