Does
select("core/editor").getEditedPostAttribute("meta")
get the
whole post meta?
Only the meta registered using register_post_meta()
or register_meta()
with the show_in_rest
argument set to true
. So for example, the meta can be registered like so:
register_post_meta( 'post', '_postcode_pricing_postal_town', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
// I set this because the meta is *protected*, i.e. the key starts with a _
// (i.e. an underscore), and when the meta is protected, by default it will
// not be editable via the REST API (even if the request was authenticated).
'auth_callback' => function () {
return current_user_can( 'edit_posts' );
},
) );
How would one iterate over the resulting post meta (if it gets it all)
getting each,_postcode_pricing_
option, and creating a
<TextControl>
for each?
First off, I would suggest you to use useEntityProp
to retrieve and update the post meta — see here for more details.
Now here’s an example of how can you correctly fill the panelInputs
array with one or more <TextControl>
depending on your post meta:
const postType = useSelect(
( select ) => select( 'core/editor' ).getCurrentPostType(),
[]
);
const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
const updateMetaValue = ( key, value ) => {
// Clone the existing meta object.
const newMeta = { ...meta };
// Update the specific meta only.
newMeta[ key ] = value;
// Then set the updated meta.
setMeta( newMeta );
};
let panelInputs = [];
for ( let key in meta ) {
if ( /^_postcode_pricing_/.test( key ) ) {
panelInputs.push(
<TextControl
label={ key }
value={ meta[ key ] }
onChange={ ( value ) => updateMetaValue( key, value ) }
/>
);
}
}
Don’t forget to load the useEntityProp
, e.g. import { useEntityProp } from '@wordpress/core-data';
.
And in the above example, the <input>
‘s label is the meta key.. but I think you’re able of changing that on your own?