Blocks: Introduce filter to allow easy addition of hooked blocks.

Introduce a `hooked_block_types` filter that allows easier conditional addition (or removal) of hooked blocks for a given anchor block and relative position.

{{{#!php
function insert_shopping_cart_hooked_block( $hooked_blocks, $position, $anchor_block, $context ) {
	if ( 'after' === $position && 'core/navigation' === $anchor_block && /** $context is header template part **/ ) {
		$hooked_blocks[] = 'mycommerce/shopping-cart';
	}
	return $hooked_blocks;
}
add_filter( 'hooked_block_types', 'insert_shopping_cart_hooked_block', 10, 4 );
}}}

Props gziolo, nerrad, dmsnell, ndiego.
Fixes #59424.

git-svn-id: https://develop.svn.wordpress.org/trunk@56673 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Bernie Reiter
2023-09-25 08:42:45 +00:00
parent cc40da134e
commit 75c06d620c
2 changed files with 90 additions and 50 deletions

View File

@@ -49,8 +49,9 @@ class Tests_Blocks_BlockHooks extends WP_UnitTestCase {
'tests/injected-one',
array(
'block_hooks' => array(
'tests/hooked-at-before' => 'before',
'tests/hooked-at-after' => 'after',
'tests/hooked-at-before' => 'before',
'tests/hooked-at-after' => 'after',
'tests/hooked-at-before-and-after' => 'before',
),
)
);
@@ -58,10 +59,11 @@ class Tests_Blocks_BlockHooks extends WP_UnitTestCase {
'tests/injected-two',
array(
'block_hooks' => array(
'tests/hooked-at-before' => 'before',
'tests/hooked-at-after' => 'after',
'tests/hooked-at-first-child' => 'first_child',
'tests/hooked-at-last-child' => 'last_child',
'tests/hooked-at-before' => 'before',
'tests/hooked-at-after' => 'after',
'tests/hooked-at-before-and-after' => 'after',
'tests/hooked-at-first-child' => 'first_child',
'tests/hooked-at-last-child' => 'last_child',
),
)
);
@@ -96,5 +98,20 @@ class Tests_Blocks_BlockHooks extends WP_UnitTestCase {
get_hooked_blocks( 'tests/hooked-at-last-child' ),
'block hooked at the last child position'
);
$this->assertSame(
array(
'tests/injected-one' => 'before',
'tests/injected-two' => 'after',
),
get_hooked_blocks( 'tests/hooked-at-before-and-after' ),
'block hooked before one block and after another'
);
$this->assertSame(
array(
'tests/injected-one' => 'before',
),
get_hooked_blocks( 'tests/hooked-at-before-and-after', 'before' ),
'block hooked before one block and after another, filtered for before'
);
}
}