Skip to content

Commit

Permalink
Block API: Block Context: Support filtering default context
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed May 6, 2020
1 parent 8d1b1b8 commit a862753
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/compat.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@ function gutenberg_render_block_with_assigned_block_context( $pre_render, $parse

/** This filter is documented in src/wp-includes/blocks.php */
$parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block );
$context = array(

$context = array(
'postId' => $post->ID,

/*
Expand All @@ -218,7 +219,16 @@ function gutenberg_render_block_with_assigned_block_context( $pre_render, $parse
*/
'postType' => $post->post_type,
);
$block = new WP_Block( $parsed_block, $context );

/**
* Filters the default context provided to a rendered block.
*
* @param array $context Default context.
* @param array $parsed_block Block being rendered, filtered by `render_block_data`.
*/
$context = apply_filters( 'render_block_context', $context, $parsed_block );

$block = new WP_Block( $parsed_block, $context );

return $block->render();
}
Expand Down
34 changes: 34 additions & 0 deletions phpunit/class-block-context-test.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,38 @@ function test_provides_default_context() {
);
}

/**
* Tests that default block context can be filtered.
*/
function test_default_context_is_filterable() {
$provided_context = array();

$this->register_block_type(
'gutenberg/test-context-consumer',
array(
'context' => array( 'example' ),
'render_callback' => function( $attributes, $content, $block ) use ( &$provided_context ) {
$provided_context[] = $block->context;

return '';
},
)
);

$filter_block_context = function( $context ) {
$context['example'] = 'ok';
return $context;
};

$parsed_blocks = parse_blocks( '<!-- wp:gutenberg/test-context-consumer /-->' );

add_filter( 'render_block_context', $filter_block_context );

render_block( $parsed_blocks[0] );

remove_filter( 'render_block_context', $filter_block_context );

$this->assertEquals( array( 'example' => 'ok' ), $provided_context[0] );
}

}

0 comments on commit a862753

Please sign in to comment.