Make WordPress Core


Ignore:
Timestamp:
02/20/2024 03:20:39 PM (3 years ago)
Author:
Bernhard Reiter
Message:

Block Hooks: Allow hooked_block filters to return null.

Allow returning null from the hooked_block and hooked_block_{$hooked_block_type} filters to suppress a hooked block from being inserted. This is required to allow extenders conditionally inserting a hooked block based on e.g. the value of an attribute of the anchor block.

Props swissspidy, gziolo, joshuatf, tomjcafferkey.
Fixes 60580.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/blocks/insertHookedBlocks.php

    r57660 r57668  
    181181                );
    182182        }
     183
     184        /**
     185         * @ticket 60580
     186         *
     187         * @covers ::insert_hooked_blocks
     188         */
     189        public function test_insert_hooked_blocks_filter_can_suppress_hooked_block() {
     190                $anchor_block = array(
     191                        'blockName'    => self::ANCHOR_BLOCK_TYPE,
     192                        'attrs'        => array(
     193                                'layout' => array(
     194                                        'type' => 'flex',
     195                                ),
     196                        ),
     197                        'innerContent' => array(),
     198                );
     199
     200                $filter = function ( $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block ) {
     201                        // Is the hooked block adjacent to the anchor block?
     202                        if ( 'before' !== $relative_position && 'after' !== $relative_position ) {
     203                                return $parsed_hooked_block;
     204                        }
     205
     206                        if (
     207                                isset( $parsed_anchor_block['attrs']['layout']['type'] ) &&
     208                                'flex' === $parsed_anchor_block['attrs']['layout']['type']
     209                        ) {
     210                                return null;
     211                        }
     212
     213                        return $parsed_hooked_block;
     214                };
     215                add_filter( 'hooked_block_' . self::HOOKED_BLOCK_TYPE, $filter, 10, 4 );
     216                $actual = insert_hooked_blocks( $anchor_block, 'after', self::HOOKED_BLOCKS, array() );
     217                remove_filter( 'hooked_block_' . self::HOOKED_BLOCK_TYPE, $filter );
     218
     219                $this->assertSame( '', $actual, "No markup should've been generated for hooked block suppressed by filter." );
     220        }
    183221}
Note: See TracChangeset for help on using the changeset viewer.