Code Examples for Parsing and Rendering Gutenberg Blocks

There are 2 functions that are really useful for WordPress developers to know when working with Gutenberg block content at a code level. The first is parse_blocks(). This enables you to parse the blocks out of any content, for example if you take any post that has been Gutenberg edited, you could use parse_blocks( $post->post_content ) to parse blocks out of the content directly.

The second very handle function for working with Gutenberg blocks at a code level is render_block(). Note this is for rendering a single blocks and not multiple blocks (the way I many times tried to use it. In the scenario that you’ve parsed some blocks into an array using parse_blocks(), you would then need to loop over your blocks in order to render them with render_block( $block ).

A minimal example here that puts these 2 functions to work in a similar way to how core itself renders Gutenberg block content (but simplified) is below:

$post_id = 100; // This will work if you have a post with ID 100, if not you'll need to figure out how to resolve this quandary on your own. 
$post = get_post( $post_id );
$blocks = parse_blocks( $post->post_content );

// Next we loop over the blocks stored in $blocks as an array. 
if( ! empty( $blocks ) ) { // Good practice here to just check before looping that we don't have an empty array. 

  foreach( $blocks as $block_index => $block ) {
    
    $block_content = render_block( $block ); 
    print $block_content; 

  }

}

In the example above we immediately printed out the block content but if we working in an AJAX response or assembling a template using object buffering (using ob_start() for instance) then we may want to stash the block content and render it later.

It’s worth getting familiar with how a block looks after parsing, which is easy enough to do again by parsing any post block and then var_dump( $block ) to see how the array is structured.

Some of the techniques you might consider using when looping over blocks before render include:

  • Injecting other content, for example an advertising or CTA display after x-number of blocks.
  • Blocking the display of a block for some reasons such as permissions, checking if user logged in and if not filter out the block from rendering.
  • Add additional classes to blocks in a given context during rendering.
  • Dynamically switch the type or style of block based on the rendering context.

Similar Posts

Leave a Reply

Your email address will not be published.