From 1e7d5594446140acaf3fd9f3f71f1d0b39469d74 Mon Sep 17 00:00:00 2001 From: Tonya Mork Date: Tue, 11 Jan 2022 15:57:09 +0000 Subject: [PATCH] Editor: Fix enqueueing additional styles in `wp_enqueue_block_style()` to print only when blocks render. In a block theme, additional block styles registered using the `wp_enqueue_block_style` function should only get printed when the block exists on a page. However, they currently always get rendered. This commit is a backport from Gutenberg that fixes the issue by printing the styles when a block renders. Follow-up to [52069]. Props poena, aristath, Mamaduka. Fixes #54787. git-svn-id: https://develop.svn.wordpress.org/trunk@52556 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/blocks.php | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/blocks.php b/src/wp-includes/blocks.php index 0f34aac1df..d6d73bdfe8 100644 --- a/src/wp-includes/blocks.php +++ b/src/wp-includes/blocks.php @@ -1254,7 +1254,31 @@ function wp_enqueue_block_style( $block_name, $args ) { $hook = did_action( 'wp_enqueue_scripts' ) ? 'wp_footer' : 'wp_enqueue_scripts'; if ( wp_should_load_separate_core_block_assets() ) { - $hook = "render_block_$block_name"; + /** + * Callback function to register and enqueue styles. + * + * @param string $content The block content. + * @param array $block The full block, including name and attributes. + * @return string Block content. + */ + $callback_separate = static function( $content, $block ) use ( $block_name, $callback ) { + if ( ! empty( $block['blockName'] ) && $block_name === $block['blockName'] ) { + return $callback( $content ); + } + return $content; + }; + + /* + * The filter's callback here is an anonymous function because + * using a named function in this case is not possible. + * + * The function cannot be unhooked, however, users are still able + * to dequeue the stylesheets registered/enqueued by the callback + * which is why in this case, using an anonymous function + * was deemed acceptable. + */ + add_filter( 'render_block', $callback_separate, 10, 2 ); + return; } /*