Filter the content to put an Gutenberg editor block’s attributes on the front end (part 3 of 4)

On the front end, I need access to the block’s attributes so I can use those in building the front end block. Instead of rendering the block as normal (either as a dynamic block or saved html), I’ll put in a filter to render something which looks like this:

  class="porchy clickgame" 

The filter I’ll use is render_block. I don’t want to register the block as a server side render because that will affect the editor, so I’ll just hijack it here. Plus it’s a bit more straightforward to me.

 * Hijack the rendering of these blocks, making a div which we will fill with our little app.
 * @param null  $render A trigger to stop the block rendering process.
 * @param array $block The array of the block data generated by the block editor.
 * @return null|string If this is null, rendering continues in core, otherwise it uses the html string sent.
function hijack_render_blocks( $render, $block ){
	$block_name = $block['blockName'];

	// This could be teased out as something in the individual block.
	// Add blocks to this array to keep them unrendered by the content filters.
	$blocks_to_hijack = [

	if ( in_array( $block_name, $blocks_to_hijack, true ) ) {
		$attributes = wp_json_encode( $block['attrs'] );
		// I'm skipping innerContent, innerHTML and innerBlocks for now because I'm not using them.
		$classes = esc_html( str_replace( '/', ' ', $block['blockName'] ) ); // A bit delicate maybe.
		$render = "<div class='$classes' data-attr='$attributes' data-block='$block_name'></div>";
	return $render;
add_filter( 'render_block',  __NAMESPACE__ . '\hijack_render_blocks', 10, 2 );

I’ve added that to the plugin.php and that’s all I need to do to get the block html on the front end as I’d like it!

You can see what I’ve added here and the state of the repo at this point in time here.

Posts on this

Leave a Reply

Your email address will not be published. Required fields are marked *

By submitting this comment, you are agreeing to the use of Akismet which helps reduce spam. You can view Akismet’s privacy policy here. Your email, website and name are also stored on this site.