serialize_blocks( WP_Block_Parser_Block[] $blocks )

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


Parameters Parameters

$blocks

(WP_Block_Parser_Block[]) (Required) Parsed block objects.


Top ↑

Return Return

(string) String of rendered HTML.


Top ↑

Source Source

File: wp-includes/blocks.php

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

Top ↑

Changelog Changelog

Changelog
Version Description
5.3.1 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by si3ard

    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/', $attachmentID );
    			$savedCaption   = wp_get_attachment_caption( $attachmentID );
    			$galleryCaption = preg_match_all( $pattern, $block['innerHTML'], $matches );
    
    			// First check if the Gallery has a caption but the Attachment doesn't,
    			// then check if the Attachent has a caption but the Gallery doesn't.
    			if ( empty( $savedCaption ) && $galleryCaption ) {
    
    				// Immediately update the attachment's missing caption.
    				$this->_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).

Top ↑

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