函数文档

serialize_blocks()

💡 云策文档标注

概述

serialize_blocks() 函数用于将解析后的块数组序列化为一个连接的 HTML 字符串。它通过调用 serialize_block() 处理每个块,适用于在修改块内容后重新生成文章内容。

关键要点

  • 参数 $blocks 是一个必需数组,包含解析后的块结构,每个块具有 blockName、attrs、innerBlocks、innerHTML 和 innerContent 等属性。
  • 返回值为字符串,表示渲染后的 HTML,可直接用于更新文章内容。
  • 函数内部使用 implode() 和 array_map('serialize_block', $blocks) 实现序列化。
  • 常用于与 wp_update_post() 结合,在保存文章时动态调整块内容,如示例中的图库标题同步场景。

代码示例

class WPDocs_Gallery_Caption_Demo {
    // 类实现用于同步图库块和附件标题
    private $_missingBlockCaptions;

    function __construct() {
        add_action('save_post', array($this, 'filterGalleries'), 10, 2);
    }

    public function filterGalleries($post_id, $post) {
        $this->_missingBlockCaptions = [];
        $blocks = parse_blocks($post->post_content);
        foreach ($blocks as $i => $block) {
            if ('core/gallery' === $block['blockName']) {
                $this->_checkCaptions($post, $block, $i);
            }
        }
        if (!empty($this->_missingBlockCaptions)) {
            $this->_addBlockCaptions($post);
        }
    }

    private function _addBlockCaptions($post) {
        $blocks = parse_blocks($post->post_content);
        foreach ($this->_missingBlockCaptions as $blockIndex => $missingCaptions) {
            foreach ($missingCaptions as $attachmentID => $caption) {
                $pattern = sprintf('/(wp-image-%s"/>)/', $attachmentID);
                $replace = sprintf('$1<figcaption>%s</figcaption>', $caption);
                $blocks[$blockIndex]['innerContent'][0] = preg_replace($pattern, $replace, $blocks[$blockIndex]['innerContent'][0]);
            }
        }
        $content = serialize_blocks($blocks);
        $updatedPost = array(
            'ID' => $post->ID,
            'post_content' => $content
        );
        wp_update_post($updatedPost);
    }
}

注意事项

  • serialize_blocks() 自 WordPress 5.3.1 版本引入,确保在兼容版本中使用。
  • 在修改块内容时,需先使用 parse_blocks() 解析文章内容,再调用 serialize_blocks() 重新序列化以更新数据库。
  • 示例代码展示了如何同步图库块中的静态标题与附件标题,避免数据不一致问题。

📄 原文内容

Returns a joined string of the aggregate serialization of the given parsed blocks.

Parameters

$blocksarray[]required
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.

Return

string String of rendered HTML.

Source

function serialize_blocks( $blocks ) {
	return implode( '', array_map( 'serialize_block', $blocks ) );
}

Changelog

Version Description
5.3.1 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Used with wp_update_post()

    Sample of how to use serialize_blocks() after making adjustments to a post’s block content.

    In this use case, I wanted to create a cross-reference between the captions used on media in a gallery, and the captions saved to the media’s corresponding Attachment post. These can easily get out of date if a user is only managing them in one place or the other.

    class WPDocs_Gallery_Caption_Demo {
    
    	// Property used for storing attachment captions
    	// that need to be added to gallery block content
    	private $_missingBlockCaptions;
    
    	function __construct() {
    
    		add_action( 'save_post', array( $this, 'filterGalleries' ), 10, 2 );
    
    	}
    
    	public function filterGalleries( $post_id, $post ) {
    
    		// Reset this property on each save.
    		$this->_missingBlockCaptions = [];
    
    		// Fetch parsed blocks from the post's saved content
    		$blocks = parse_blocks( $post->post_content );
    
    		// Check for missing captions if a Gallery Block is used on the page.
    		// Also pass along the index of the block for use in editing content later
    		foreach ( $blocks as $i => $block ) {
    
    			if ( 'core/gallery' === $block['blockName'] ) {
    
    				$this->_checkCaptions( $post, $block, $i );
    
    			}
    
    		}
    
    	}
    
    	private function _checkCaptions( $post, $block, $blockIndex ) {
    
    		foreach ( $block['attrs']['ids'] as $attachmentID ) {
    
    			$pattern        = sprintf( '/wp-image-%s"/><figcaption[^>]+>(?<caption>[^<]+)</figcaption>_updateAttachmentCaption( $attachmentID, $matches['caption'][0] );
    
    			} elseif ( ! empty( $savedCaption ) && ! $galleryCaption ) {
    
    				// Store the block index, attachment ID and caption
    				// for use later when we bulk-update the post content.
    				$this->_missingBlockCaptions[ $blockIndex ][ $attachmentID ] = $savedCaption;
    
    			}
    
    		}
    
    		// Use a bulk method to update multiple missing captions in the post content
    		// for the Attachments that have a caption in their `post_excerpt` value,
    		// since this is one `post_content` value for multiple media attachments.
    		if ( ! empty( $this->_missingBlockCaptions ) ) {
    			$this->_addBlockCaptions( $post );
    		}
    
    	}
    
    	private function _updateAttachmentCaption( $attachmentID, $caption ) {
    
    		wp_update_post( array(
    			'ID'            => $attachmentID,
    			'post_excerpt'  => $caption
    		) );
    
    	}
    
    	private function _addBlockCaptions( $post ) {
    
    		// Parse out the blocks so we can update the `innerContent`
    		// for the corresponding indices stored $missingBlockCaptions.
    		$blocks = parse_blocks( $post->post_content );
    
    		foreach ( $this->_missingBlockCaptions as $blockIndex => $missingCaptions ) {
    
    			foreach ( $misingCaptions as $attachmentID => $caption ) {
    
    				// Match the end of the target img tag using its saved ID.
    				$pattern = sprintf( '/(wp-image-%s"/>)/', $attachmentID );
    
    				// Add the missing figcaption markup, using the saved caption
    				// from the Attachment's `post_excerpt` value we got in $this->checkCaptions()
    				$replace = sprintf( '$1<figcaption class="blocks-gallery-item__caption">%s</figcaption>', $caption );
    
    				// Insert our new figcaption markup into the target block
    				// using the $blockIndex reference.
    				$blocks[ $blockIndex ]['innerContent'][0] = preg_replace( $pattern, $replace, $blocks[ $blockIndex ]['innerContent'][0] );
    
    			}
    
    		}
    
    		// Using `serialize_blocks` will handle `serialize_block`
    		// for each block in $blocks.
    		$content = serialize_blocks( $blocks );
    		$updatedPost = array(
    			'ID'            => $post->ID,
    			'post_content'  => $content
    		);
    
    		// Update the post with the new adjustments made to the gallery blocks' `innerContent`
    		wp_update_post( $updatedPost );
    
    	}
    
    }
    
    new WPDocs_Gallery_Caption_Demo();

    Gallery blocks have a caption field on the block editor view that is static to the block and does not save back to the original Attachment. This class updates the Attachment’s caption if it is empty while a static one was written in the a gallery block. It also does the converse; it adds a tag with the Attachment’s caption value to the gallery items that don’t have a static caption written on them.

    The functional use for this is to update the captions into the database so that the user will see them on page reload, instead of trusting that they will show up only in the front end (using the render_block filter).

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