render_block_context filter and block context inheritance

Presumably, within your Query Loop block, you also have a Post Template block. When rendering the page server side, there is “barrier” in the context inheritance caused by the render_block_core_post_template():

$block_content = ( new WP_Block( $block_instance ) )->render( array( 'dynamic' => false ) );

It renders the content without any of its context (it is the second parameter to the WP_Block constructor).

Hence, we need to “save” the context value and pass them through this barrier. We can do this by hooking into render_block_context for child blocks. We do this by adding this hook just before the Post Template block is rendered and then remove the hook after rendering it:

// render_block_data is the last hook just before a block is rendered.
add_filter(
  'render_block_data',
  function( $block ) {
    if ( $block['blockName'] === 'core/post-template' ) {
      // This will add the context for any child block within this
      // `core/post-template` block we are about to render.
      $add_context = function ( $context ) {
        $context['helga/tacos'] = 'we love tacos';
        return $context;
      };
      add_filter( 'render_block_context', $add_context );

      // Unhook the context filter above, after rendering this
      // `core/post-template` block.
      $unhook = function ( $content ) use ( &$unhook, $add_context ) {
        // Unhook.
        remove_filter( 'render_block_context', $add_context );
        // Unhook this function too since it is no longer needed.
        remove_filter( 'render_block_core/post-template', $unhook );

        return $content;
      };
      add_filter( 'render_block_core/post-template', $unhook );
    }

    return $block;
  }
);

techhipbettruvabetnorabahisbahis forumutaraftarium24edueduedusedusedusedusedueduedusedus