From b6a04b3b28307bdedd34395b56cb140536257775 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Mon, 1 Feb 2021 18:04:36 +0000 Subject: [PATCH] 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. git-svn-id: https://develop.svn.wordpress.org/trunk@50123 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-block.php | 17 ++++++++++++++++- tests/phpunit/tests/blocks/block.php | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-block.php b/src/wp-includes/class-wp-block.php index 10c7d92dcd..6926abf3f4 100644 --- a/src/wp-includes/class-wp-block.php +++ b/src/wp-includes/class-wp-block.php @@ -241,7 +241,22 @@ class WP_Block { * @param string $block_content The block content about to be appended. * @param array $block The full block, including name and attributes. */ - return apply_filters( 'render_block', $block_content, $this->parsed_block ); + $block_content = apply_filters( 'render_block', $block_content, $this->parsed_block ); + + /** + * Filters the content of a single block. + * + * The dynamic portion of the hook name, `$name`, refers to + * the block name, e.g. "core/paragraph". + * + * @since 5.7.0 + * + * @param string $block_content The block content about to be appended. + * @param array $block The full block, including name and attributes. + */ + $block_content = apply_filters( "render_block_{$this->name}", $block_content, $this->parsed_block ); + + return $block_content; } } diff --git a/tests/phpunit/tests/blocks/block.php b/tests/phpunit/tests/blocks/block.php index afb422ca0d..84e2ff903a 100644 --- a/tests/phpunit/tests/blocks/block.php +++ b/tests/phpunit/tests/blocks/block.php @@ -328,7 +328,26 @@ class WP_Block_Test extends WP_UnitTestCase { remove_filter( 'render_block', array( $this, 'filter_render_block' ) ); $this->assertSame( 'Original: "StaticOriginal: "Inner", from block "core/example"", from block "core/example"', $rendered_content ); + } + /** + * @ticket 46187 + */ + function test_render_applies_dynamic_render_block_filter() { + $this->registry->register( 'core/example', array() ); + + add_filter( 'render_block_core/example', array( $this, 'filter_render_block' ), 10, 2 ); + + $parsed_blocks = parse_blocks( 'StaticInner' ); + $parsed_block = $parsed_blocks[0]; + $context = array(); + $block = new WP_Block( $parsed_block, $context, $this->registry ); + + $rendered_content = $block->render(); + + remove_filter( 'render_block_core/example', array( $this, 'filter_render_block' ) ); + + $this->assertSame( 'Original: "StaticOriginal: "Inner", from block "core/example"", from block "core/example"', $rendered_content ); } /**