Skip to content

Commit

Permalink
Don't insert block if multiple:false and another instance is already …
Browse files Browse the repository at this point in the history
…present
  • Loading branch information
ockham committed Sep 18, 2024
1 parent 756a8b2 commit ee1ce79
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/wp-includes/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,29 @@ function insert_hooked_blocks( &$parsed_anchor_block, $relative_position, $hooke

$markup = '';
foreach ( $hooked_block_types as $hooked_block_type ) {
$hooked_block_type_definition = WP_Block_Type_Registry::get_instance()->get_registered( $hooked_block_type );
if ( ! $hooked_block_type_definition ) {
continue;
}
if ( false === block_has_support( $hooked_block_type_definition, 'multiple', true ) ) {
if ( $context instanceof WP_Block_Template ) {
// Template or template part.
$content = $context->content;
} elseif ( $context instanceof WP_Post ) {
// wp_navigation post.
$content = $context->post_content;
} elseif ( is_array( $context ) && isset( $context['content'] ) ) {
// Pattern.
$content = $context['content'];
} else {
$content = '';
}

if ( ! empty( $content ) && has_block( $hooked_block_type, $content ) ) {
continue;
}
}

$parsed_hooked_block = array(
'blockName' => $hooked_block_type,
'attrs' => array(),
Expand Down
25 changes: 25 additions & 0 deletions tests/phpunit/tests/blocks/insertHookedBlocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ public static function wpSetUpBeforeClass() {
'block_hooks' => array(
self::ANCHOR_BLOCK_TYPE => 'before',
),
'supports' => array(
'multiple' => false,
),
)
);
}
Expand Down Expand Up @@ -122,6 +125,28 @@ public function test_insert_hooked_blocks_if_other_block_is_ignored() {
);
}

/**
* @ticket 61902
*
* @covers ::insert_hooked_blocks
*/
public function test_insert_hooked_blocks_if_block_has_multiple_false_and_is_already_present() {
$anchor_block = array(
'blockName' => 'tests/anchor-block',
);

$context = new WP_Block_Template();
$context->content = '<!-- wp:' . self::ANCHOR_BLOCK_TYPE . ' /-->';
$context->content .= '<!-- wp:' . self::OTHER_HOOKED_BLOCK_TYPE . ' /-->';

$actual = insert_hooked_blocks( $anchor_block, 'before', get_hooked_blocks(), $context );
$this->assertSame(
'',
$actual,
'Hooked block with "multiple": false should not be inserted if another instance is already present.'
);
}

/**
* @ticket 59572
* @ticket 60126
Expand Down

0 comments on commit ee1ce79

Please sign in to comment.