diff --git a/src/wp-includes/block-template-utils.php b/src/wp-includes/block-template-utils.php index b8538ee3b43e2..360d2419b4979 100644 --- a/src/wp-includes/block-template-utils.php +++ b/src/wp-includes/block-template-utils.php @@ -513,6 +513,26 @@ function _inject_theme_attribute_in_block_template_content( $template_content ) return $template_content; } +/** + * Injects the active theme's stylesheet as a `theme` attribute + * into a given template part block. + * + * @since 6.4.0 + * @access private + * + * @param array $block a parsed block. + * @return array Updated block. + */ +function _inject_theme_attribute_in_block_template_block( $block ) { + if ( + 'core/template-part' === $block['blockName'] && + ! isset( $block['attrs']['theme'] ) + ) { + $block['attrs']['theme'] = get_stylesheet(); + } + return $block; +} + /** * Parses a block template and removes the theme attribute from each template part. * @@ -565,7 +585,6 @@ function _build_block_template_result_from_file( $template_file, $template_type $template = new WP_Block_Template(); $template->id = $theme . '//' . $template_file['slug']; $template->theme = $theme; - $template->content = _inject_theme_attribute_in_block_template_content( $template_content ); $template->slug = $template_file['slug']; $template->source = 'theme'; $template->type = $template_type; @@ -589,6 +608,9 @@ function _build_block_template_result_from_file( $template_file, $template_type $template->area = $template_file['area']; } + $blocks = parse_blocks( $template_content ); + $template->content = serialize_blocks( $blocks, '_inject_theme_attribute_in_block_template_block' ); + return $template; } diff --git a/src/wp-includes/blocks.php b/src/wp-includes/blocks.php index 4d3a34e34fa77..c92ea78562f8a 100644 --- a/src/wp-includes/blocks.php +++ b/src/wp-includes/blocks.php @@ -794,16 +794,22 @@ function get_comment_delimited_block_content( $block_name, $block_attributes, $b * instead preserve the markup as parsed. * * @since 5.3.1 + * @since 6.4.0 The `$callback` parameter was added. * * @param array $block A representative array of a single parsed block object. See WP_Block_Parser_Block. + * @param string $callback Optional. Callback to run on the block before serialization. * @return string String of rendered HTML. */ -function serialize_block( $block ) { +function serialize_block( $block, $callback = null ) { + if ( is_callable( $callback ) ) { + $block = call_user_func( $callback, $block ); + } + $block_content = ''; $index = 0; foreach ( $block['innerContent'] as $chunk ) { - $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] ); + $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ], $callback ); } if ( ! is_array( $block['attrs'] ) ) {