From 7bb8050f1d81d74f80732900aa658093c97deda3 Mon Sep 17 00:00:00 2001 From: Dennis Snell Date: Mon, 12 Nov 2018 12:35:37 -0500 Subject: [PATCH] Block Rendering: Add pre-render and post-render filteres Allows for blocks to be structurally and textually filtered during the rendering process. The pre-filter provides the parsed block object for transformation while the post-filter provides the rendered output of the block. These filters can be used in unison to perform a variety of operations on blocks. They are applied in a depth-first manner when rendering a block tree so that deeper-nested blocks are processed before their parents. > Caveat: Inner blocks aren't structurally filtered in this patch yet before their parent. Actually this needs a lot of work still... --- lib/blocks.php | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/blocks.php b/lib/blocks.php index a8083466a04053..10446a414a7cb8 100644 --- a/lib/blocks.php +++ b/lib/blocks.php @@ -142,25 +142,37 @@ function get_dynamic_blocks_regex() { function gutenberg_render_block( $block ) { global $post; - $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] ); - $is_dynamic = $block['blockName'] && null !== $block_type && $block_type->is_dynamic(); + $global_post = $post; + $pre_render = apply_filters( 'block_pre_render', $block ); + $post = $global_post; + + if ( null === $pre_render ) { + return ''; + } + + $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $pre_render['blockName'] ); + $is_dynamic = $pre_render['blockName'] && null !== $block_type && $block_type->is_dynamic(); $inner_content = ''; $index = 0; - foreach ( $block['innerContent'] as $chunk ) { - $inner_content .= is_string( $chunk ) ? $chunk : gutenberg_render_block( $block['innerBlocks'][ $index++ ] ); + foreach ( $pre_render['innerContent'] as $chunk ) { + $inner_content .= is_string( $chunk ) ? $chunk : gutenberg_render_block( $pre_render['innerBlocks'][ $index++ ] ); } if ( $is_dynamic ) { - $attributes = is_array( $block['attrs'] ) ? (array) $block['attrs'] : array(); + $attributes = is_array( $pre_render['attrs'] ) ? (array) $pre_render['attrs'] : array(); $global_post = $post; $output = $block_type->render( $attributes, $inner_content ); $post = $global_post; - - return $output; + } else { + $output = $inner_content; } - return $inner_content; + $global_post = $post; + $post_render = apply_filters( 'block_post_render', $output ); + $post = $global_post; + + return $post_render; } if ( ! function_exists( 'do_blocks' ) ) {