diff --git a/packages/block-library/src/pattern/edit.js b/packages/block-library/src/pattern/edit.js index 641280bb8a9d59..d9f0c2c53cebcd 100644 --- a/packages/block-library/src/pattern/edit.js +++ b/packages/block-library/src/pattern/edit.js @@ -8,6 +8,7 @@ import { store as blockEditorStore, useBlockProps, } from '@wordpress/block-editor'; +import { store as coreStore } from '@wordpress/core-data'; const PatternEdit = ( { attributes, clientId } ) => { const selectedPattern = useSelect( @@ -18,12 +19,42 @@ const PatternEdit = ( { attributes, clientId } ) => { [ attributes.slug ] ); + const currentThemeStylesheet = useSelect( + ( select ) => select( coreStore ).getCurrentTheme().stylesheet + ); + const { replaceBlocks, __unstableMarkNextChangeAsNotPersistent } = useDispatch( blockEditorStore ); const { setBlockEditingMode } = useDispatch( blockEditorStore ); const { getBlockRootClientId, getBlockEditingMode } = useSelect( blockEditorStore ); + function injectThemeAttributeInBlockTemplateContent( block ) { + if ( + block.innerBlocks.find( + ( innerBlock ) => innerBlock.name === 'core/template-part' + ) + ) { + block.innerBlocks = block.innerBlocks.map( ( innerBlock ) => { + if ( + innerBlock.name === 'core/template-part' && + innerBlock.attributes.theme === undefined + ) { + innerBlock.attributes.theme = currentThemeStylesheet; + } + return innerBlock; + } ); + } + + if ( + block.name === 'core/template-part' && + block.attributes.theme === undefined + ) { + block.attributes.theme = currentThemeStylesheet; + } + return block; + } + // Run this effect when the component loads. // This adds the Pattern's contents to the post. // This change won't be saved. @@ -40,7 +71,9 @@ const PatternEdit = ( { attributes, clientId } ) => { // Clone blocks from the pattern before insertion to ensure they receive // distinct client ids. See https://github.com/WordPress/gutenberg/issues/50628. const clonedBlocks = selectedPattern.blocks.map( ( block ) => - cloneBlock( block ) + cloneBlock( + injectThemeAttributeInBlockTemplateContent( block ) + ) ); const rootEditingMode = getBlockEditingMode( rootClientId ); // Temporarily set the root block to default mode to allow replacing the pattern. diff --git a/packages/block-library/src/pattern/index.php b/packages/block-library/src/pattern/index.php index bc42e891d9f1fd..97a8c3ddc663f8 100644 --- a/packages/block-library/src/pattern/index.php +++ b/packages/block-library/src/pattern/index.php @@ -41,7 +41,7 @@ function render_block_core_pattern( $attributes ) { } $pattern = $registry->get_registered( $slug ); - $content = $pattern['content']; + $content = _inject_theme_attribute_in_block_template_content( $pattern['content'] ); $gutenberg_experiments = get_option( 'gutenberg-experiments' ); if ( $gutenberg_experiments && ! empty( $gutenberg_experiments['gutenberg-auto-inserting-blocks'] ) ) {