diff --git a/packages/editor/src/components/provider/index.js b/packages/editor/src/components/provider/index.js index aaf25621d3324b..654fecf2d3ecfe 100644 --- a/packages/editor/src/components/provider/index.js +++ b/packages/editor/src/components/provider/index.js @@ -4,7 +4,11 @@ import { useEffect, useLayoutEffect, useMemo } from '@wordpress/element'; import { useDispatch, useSelect } from '@wordpress/data'; import { __ } from '@wordpress/i18n'; -import { EntityProvider, useEntityBlockEditor } from '@wordpress/core-data'; +import { + EntityProvider, + useEntityBlockEditor, + store as coreStore, +} from '@wordpress/core-data'; import { BlockEditorProvider, BlockContextProvider, @@ -48,7 +52,6 @@ const noop = () => {}; */ const NON_CONTEXTUAL_POST_TYPES = [ 'wp_block', - 'wp_template', 'wp_navigation', 'wp_template_part', ]; @@ -161,31 +164,57 @@ export const ExperimentalEditorProvider = withRegistryProvider( BlockEditorProviderComponent = ExperimentalBlockEditorProvider, __unstableTemplate: template, } ) => { - const { editorSettings, selection, isReady, mode } = useSelect( - ( select ) => { + const { editorSettings, selection, isReady, mode, postTypes } = + useSelect( ( select ) => { const { getEditorSettings, getEditorSelection, getRenderingMode, __unstableIsEditorReady, } = select( editorStore ); + const { getPostTypes } = select( coreStore ); + return { editorSettings: getEditorSettings(), isReady: __unstableIsEditorReady(), mode: getRenderingMode(), selection: getEditorSelection(), + postTypes: + getPostTypes( { per_page: -1 } )?.map( + ( entity ) => entity.slug + ) || [], }; - }, - [] - ); + }, [] ); const shouldRenderTemplate = !! template && mode !== 'post-only'; const rootLevelPost = shouldRenderTemplate ? template : post; const defaultBlockContext = useMemo( () => { - const postContext = + const postContext = {}; + // If it is a template, try to inherit the post type from the slug. + if ( post.type === 'wp_template' ) { + if ( ! post.is_custom ) { + const [ kind ] = post.slug.split( '-' ); + switch ( kind ) { + case 'page': + postContext.postType = 'page'; + break; + case 'single': + // Infer the post type from the slug. + const match = post.slug.match( + `^single-(${ postTypes.join( '|' ) })(?:-.+)?$` + ); + if ( match ) { + postContext.postType = match[ 1 ]; + } + break; + } + } + } else if ( ! NON_CONTEXTUAL_POST_TYPES.includes( rootLevelPost.type ) || shouldRenderTemplate - ? { postId: post.id, postType: post.type } - : {}; + ) { + postContext.postId = post.id; + postContext.postType = post.type; + } return { ...postContext, @@ -200,6 +229,7 @@ export const ExperimentalEditorProvider = withRegistryProvider( post.type, rootLevelPost.type, rootLevelPost.slug, + postTypes, ] ); const { id, type } = rootLevelPost; const blockEditorSettings = useBlockEditorSettings(