Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix enqueueing additional styles for blocks only when rendered #37848

Merged
merged 3 commits into from
Jan 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 36 additions & 5 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -605,10 +605,9 @@ function wp_enqueue_block_style( $block_name, $args ) {
* @param string $content When the callback is used for the render_block filter,
* the content needs to be returned so the function parameter
* is to ensure the content exists.
*
* @return string
* @return string Block content.
*/
$callback = function( $content ) use ( $args ) {
$callback = static function( $content ) use ( $args ) {
// Register the stylesheet.
if ( ! empty( $args['src'] ) ) {
wp_register_style( $args['handle'], $args['src'], $args['deps'], $args['ver'], $args['media'] );
Expand Down Expand Up @@ -639,10 +638,42 @@ 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;
}

// Enqueue assets in the frontend.
/*
* 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( $hook, $callback );

// Enqueue assets in the editor.
Expand Down