Skip to content

Commit b62ac07

Browse files
SantosGuillamotartemiomorales
authored andcommitted
Render the appropriate fields depending on the postType in templates
1 parent 748898b commit b62ac07

File tree

1 file changed

+53
-19
lines changed

1 file changed

+53
-19
lines changed

‎packages/editor/src/bindings/post-meta.js

+53-19
Original file line numberDiff line numberDiff line change
@@ -82,31 +82,65 @@ export default {
8282
return true;
8383
},
8484
getFieldsList( { registry, context } ) {
85-
const metaFields = registry
86-
.select( coreDataStore )
87-
.getEditedEntityRecord(
85+
let metaFields = {};
86+
const {
87+
type,
88+
is_custom: isCustom,
89+
slug,
90+
} = registry.select( editorStore ).getCurrentPost();
91+
const { getPostTypes, getEntityRecord, getEditedEntityRecord } =
92+
registry.select( coreDataStore );
93+
94+
// If it is a template, use the default values.
95+
if ( type === 'wp_template' ) {
96+
let postType;
97+
let isGlobalTemplate = false;
98+
// Get the 'kind' from the start of the slug.
99+
const [ kind ] = slug.split( '-' );
100+
if ( isCustom || slug === 'index' ) {
101+
isGlobalTemplate = true;
102+
// Use 'post' as the default.
103+
postType = 'post';
104+
} else if ( kind === 'page' ) {
105+
postType = 'page';
106+
} else if ( kind === 'single' ) {
107+
const postTypes =
108+
getPostTypes( { per_page: -1 } )?.map(
109+
( entity ) => entity.slug
110+
) || [];
111+
112+
// Infer the post type from the slug.
113+
const match = slug.match(
114+
`^single-(${ postTypes.join( '|' ) })(?:-.+)?$`
115+
);
116+
postType = match ? match[ 1 ] : 'post';
117+
}
118+
119+
// TODO: Fields returns undefined on the first click.
120+
const fields = getEntityRecord(
121+
'root',
122+
'postType',
123+
postType
124+
)?.meta;
125+
126+
// Populate the `metaFields` object with the default values.
127+
Object.entries( fields || {} ).forEach( ( [ key, props ] ) => {
128+
// If the template is global, skip the fields with a subtype.
129+
if ( isGlobalTemplate && props.subtype ) {
130+
return;
131+
}
132+
metaFields[ key ] = props.default;
133+
} );
134+
} else {
135+
metaFields = getEditedEntityRecord(
88136
'postType',
89137
context?.postType,
90138
context?.postId
91139
).meta;
92-
93-
// TODO: Fields returns undefined on the first click.
94-
const fields = registry
95-
.select( coreDataStore )
96-
// TODO: Last item 'post' should not be hardcoded.
97-
.getEntityRecord( 'root', 'postType', 'post' );
140+
}
98141

99142
if ( ! metaFields || ! Object.keys( metaFields ).length ) {
100-
if ( ! fields?.meta ) {
101-
return null;
102-
}
103-
const metaDefaults = {};
104-
for ( const key in fields.meta ) {
105-
if ( fields.meta.hasOwnProperty( key ) ) {
106-
metaDefaults[ key ] = fields.meta[ key ].default;
107-
}
108-
}
109-
return metaDefaults;
143+
return null;
110144
}
111145

112146
// Remove footnotes or private keys from the list of fields.

0 commit comments

Comments
 (0)