Notes from building dynamic Gutenberg block handling

Parsing and rendering Gutenberg blocks

Two core WP functions to remember for handling blocks with any type of custom rendering approach is first parse_blocks( $content ) which “parses blocks out of content” so given for instance a $post->post_content as the $content, parse_blocks() will return an array of $blocks. Each block in a parsed $blocks array will have some useful information, including for instance $block[‘innerBlocks’] which is any nested blocks inside this current block. Which in turn of course also might have another “innerBlocks” in it, so that’s how we would access an infinite number of nested inner blocks starting with the parent block.

The second notable function is render_block( $block ). And this takes the $block definition that you got in an array of $blocks from parse_blocks() so you can basically just run parse_blocks() and then loop over $blocks and render each block with render_block( $block ). In practice you might have something else in terms of preparation of data before you do the render_block() after doing parse_blocks().

Leave a Reply