From b5274bf2ac1cce837c4155932e10652f78647e24 Mon Sep 17 00:00:00 2001 From: Bernie Reiter Date: Thu, 4 May 2023 15:02:31 +0600 Subject: [PATCH] Post Template Block: Set block context via filter In the Post Template block's render callback, instead of creating a new `WP_Block` instance with `postId` and `postType` context set, use the `render_block_context` filter to set that context and render the existing `WP_Block` instance. This approach arguably follows our established patterns with regard to handling block context better. Notably, with the previous approach, we were only setting block context for the Post Template block itself. In this PR, we extend it to apply to all child blocks, including ones that are dynamically inserted, e.g. via the `render_block` filter. This is relevant for Auto-inserting blocks (see #50103). This follows the precedent of the Comment Template block, see #50279. --- .../block-library/src/post-template/index.php | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/packages/block-library/src/post-template/index.php b/packages/block-library/src/post-template/index.php index 3a3c207cf92ee2..779abf4c17bdb1 100644 --- a/packages/block-library/src/post-template/index.php +++ b/packages/block-library/src/post-template/index.php @@ -78,24 +78,22 @@ function render_block_core_post_template( $attributes, $content, $block ) { while ( $query->have_posts() ) { $query->the_post(); - // Get an instance of the current Post Template block. - $block_instance = $block->parsed_block; - // Set the block name to one that does not correspond to an existing registered block. // This ensures that for the inner instances of the Post Template block, we do not render any block supports. - $block_instance['blockName'] = 'core/null'; - + $block->name = 'core/null'; + + $post_id = get_the_ID(); + $post_type = get_post_type(); + $filter_block_context = static function( $context ) use ( $post_id, $post_type ) { + $context['postType'] = $post_type; + $context['postId'] = $post_id; + return $context; + }; + add_filter( 'render_block_context', $filter_block_context ); // Render the inner blocks of the Post Template block with `dynamic` set to `false` to prevent calling // `render_callback` and ensure that no wrapper markup is included. - $block_content = ( - new WP_Block( - $block_instance, - array( - 'postType' => get_post_type(), - 'postId' => get_the_ID(), - ) - ) - )->render( array( 'dynamic' => false ) ); + $block_content = $block->render( array( 'dynamic' => false ) ); + remove_filter( 'render_block_context', $filter_block_context ); // Wrap the render inner blocks in a `li` element with the appropriate post classes. $post_classes = implode( ' ', get_post_class( 'wp-block-post' ) );