Make WordPress Core

Changeset 50123


Ignore:
Timestamp:
02/01/2021 06:04:36 PM (4 years ago)
Author:
SergeyBiryukov
Message:

Editor: Introduce a dynamic filter for the content of a single block:

render_block_{$this->name}

This complements the existing render_block hook and allows for filtering the content of a specific block without having to use conditionals inside the filter callback.

Props manzoorwani.jk, noisysocks, birgire, johnbillion.
Fixes #46187.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-block.php

    r49695 r50123  
    242242         * @param array  $block         The full block, including name and attributes.
    243243         */
    244         return apply_filters( 'render_block', $block_content, $this->parsed_block );
     244        $block_content = apply_filters( 'render_block', $block_content, $this->parsed_block );
     245
     246        /**
     247         * Filters the content of a single block.
     248         *
     249         * The dynamic portion of the hook name, `$name`, refers to
     250         * the block name, e.g. "core/paragraph".
     251         *
     252         * @since 5.7.0
     253         *
     254         * @param string $block_content The block content about to be appended.
     255         * @param array  $block         The full block, including name and attributes.
     256         */
     257        $block_content = apply_filters( "render_block_{$this->name}", $block_content, $this->parsed_block );
     258
     259        return $block_content;
    245260    }
    246261
  • trunk/tests/phpunit/tests/blocks/block.php

    r49695 r50123  
    329329
    330330        $this->assertSame( 'Original: "StaticOriginal: "Inner", from block "core/example"", from block "core/example"', $rendered_content );
    331 
     331    }
     332
     333    /**
     334     * @ticket 46187
     335     */
     336    function test_render_applies_dynamic_render_block_filter() {
     337        $this->registry->register( 'core/example', array() );
     338
     339        add_filter( 'render_block_core/example', array( $this, 'filter_render_block' ), 10, 2 );
     340
     341        $parsed_blocks = parse_blocks( '<!-- wp:example -->Static<!-- wp:example -->Inner<!-- /wp:example --><!-- /wp:example -->' );
     342        $parsed_block  = $parsed_blocks[0];
     343        $context       = array();
     344        $block         = new WP_Block( $parsed_block, $context, $this->registry );
     345
     346        $rendered_content = $block->render();
     347
     348        remove_filter( 'render_block_core/example', array( $this, 'filter_render_block' ) );
     349
     350        $this->assertSame( 'Original: "StaticOriginal: "Inner", from block "core/example"", from block "core/example"', $rendered_content );
    332351    }
    333352
Note: See TracChangeset for help on using the changeset viewer.