parse_blocks()
Parses the specified string with Gutenberg markup and parses it into an array of block data.
The function builds a tree according to the specification WP_Block_Parser_Block: each node has blockName, attrs, innerBlocks, innerHTML, and innerContent. Nested blocks are stored in innerBlocks.
Useful when writing content migrations, REST endpoints, and when searching/replacing blocks in the database.
Unlike do_blocks() and render_block(), it does not output ready HTML and does not call render_callback of dynamic blocks.
Use has_blocks() / has_block() if you just need to check for the presence of blocks. They are faster.
After edits, you can get the string again using serialize_blocks() or the helper traverse_and_serialize_blocks().
Hooks from the function
Returns
Array[]. Data on the parsed blocks.
Usage
parse_blocks( $content );
- $content(string) (required)
- Content that needs to be parsed. Raw content in block notation Gutenberg
<!-- wp:... -->.
Examples
#1 Example returned data
Let us have the following content:
<!-- wp:gallery {"ids":[11]} -->
<figure class="wp-block-gallery columns-1 is-cropped">
<ul class="blocks-gallery-grid">
<li class="blocks-gallery-item">
<figure>
<img src="https://example.com/wp-content/uploads/2020/05/2020-landscape-1-1024x656.png" alt=""
data-id="11"
data-full-url="https://example.com/wp-content/uploads/2020/05/2020-landscape-1.png"
data-link="https://example.com/my-super-image/"
class="wp-image-11"/>
</figure>
</li>
</ul>
</figure>
<!-- /wp:gallery -->
<!-- wp:cover {"overlayColor":"luminous-vivid-amber"} -->
<div class="wp-block-cover has-luminous-vivid-amber-background-color has-background-dim">
<div class="wp-block-cover__inner-container">
<!-- wp:paragraph {"align": "center", "placeholder": "Enter title...", "fontSize": "large"}
<p class="has-text-align-center has-large-font-size">Super block header! </p>
<!-- /wp:paragraph -->
</div>
</div>
<!-- /wp:cover -->
<!-- wp:paragraph -->
<p>Ordinary paragraph with text</p>
<!-- /wp:paragraph -->
Let's run this content through the function
$parse_content = parse_blocks( $content ); print_r( $parse_content );
The function will return the following result:
Changelog
| Since 5.0.0 | Introduced. |
parse_blocks() parse blocks code WP 6.8.3
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 );
}