Make WordPress Core


Ignore:
Timestamp:
09/03/2024 04:31:44 PM (6 months ago)
Author:
cbravobernal
Message:

Block bindings: Adds a filter to customize the output of a block bindings source.

Introduces a filter to the block_bindings_source_value to allow developers to
modify the value returned by any block binding source.

Props snehapatil02, cbravobernal, gziolo, santosguillamot, bacoords, codersantosh.
Fixes #61181.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/block-bindings/render.php

    r58398 r58972  
    299299        );
    300300    }
     301
     302    /**
     303     * Tests that filter `block_bindings_source_value` is applied.
     304     *
     305     * @ticket 61181
     306     */
     307    public function test_filter_block_bindings_source_value() {
     308        register_block_bindings_source(
     309            self::SOURCE_NAME,
     310            array(
     311                'label'              => self::SOURCE_LABEL,
     312                'get_value_callback' => function () {
     313                    return '';
     314                },
     315            )
     316        );
     317
     318        $filter_value = function ( $value, $source_name, $source_args, $block_instance, $attribute_name ) {
     319            if ( self::SOURCE_NAME !== $source_name ) {
     320                return $value;
     321            }
     322            return "Filtered value: {$source_args['test_key']}. Block instance: {$block_instance->name}. Attribute name: {$attribute_name}.";
     323        };
     324
     325        add_filter( 'block_bindings_source_value', $filter_value, 10, 5 );
     326
     327        $block_content = <<<HTML
     328<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"test/source", "args":{"test_key":"test_arg"}}}}} -->
     329<p>Default content</p>
     330<!-- /wp:paragraph -->
     331HTML;
     332        $parsed_blocks = parse_blocks( $block_content );
     333        $block         = new WP_Block( $parsed_blocks[0] );
     334        $result        = $block->render();
     335
     336        remove_filter( 'block_bindings_source_value', $filter_value );
     337
     338        $this->assertSame(
     339            '<p>Filtered value: test_arg. Block instance: core/paragraph. Attribute name: content.</p>',
     340            trim( $result ),
     341            'The block content should show the filtered value.'
     342        );
     343    }
    301344}
Note: See TracChangeset for help on using the changeset viewer.