I’m looking for an intelligent way to iterate over available post meta, preferably by using the prefix _postcode_pricing_
, and create new <TextControl>
components for each. Really, I have two questions as I’m still fairly new to react and WordPress/scripts together.
Question One:
Does select("core/editor").getEditedPostAttribute("meta")
get the whole post meta?
Question Two:
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?
This is my current code, hopefully, you can see where I’m trying to go with it. (This snippet doesn’t work, and I don’t expect it to. I’m only providing it in the hopes it helps you understand my question.)
const TextController = (props) => {
// Get post meta
const meta = useSelect((select) =>
select("core/editor").getEditedPostAttribute("meta")
);
const { editPost } = useDispatch("core/editor");
// loop through the meta array creating textFields as we go.
var metaOptions = meta;
for ($i = 0, $size = count(metaOptions); $i < $size; ++$i) {
panelInputs.push(
<PanelRow>
<TextControl
label={__("META FIELD NAME", "postcode-pricing")}
value={meta}
class={"metaControl-".i} // note: using class to allow react to uniquely identify each element
onChange={(value) =>
editPost({ meta: { _postcode_pricing_META_FIELD_NAME: value } })
}
/>
</PanelRow>
);
}
return <div>{panelInputs}</div>;
};
My Current JSON output – example.com/wp-json/wp/v2/postcode_pricing_pt/POST-ID
"meta": {
"_generate-full-width-content": "",
"_postcode_pricing_outward_code": "", // <-- I only want to grab the following lines
"_postcode_pricing_postal_town": "", // <--
"_postcode_pricing_postal_county": "", // <--
"_postcode_pricing_auto_1hr": "", // <--
"_postcode_pricing_auto_5hr": "", // <--
"_postcode_pricing_auto_10hr": "", // <--
"_postcode_pricing_auto_weekend_evening": "", // <--
"_postcode_pricing_manual_1hr": "", // <--
"_postcode_pricing_manual_5hr": "", // <--
"_postcode_pricing_manual_10hr": "", // <--
"_postcode_pricing_manual_weekend_evening": "" // <--
},
My Meta Registration
/**
* Registers postcode_pricing_pt meta data
*
* @since 1.0.0
*/
public function postcode_pricing_register_meta() {
// Meta array.
$postcodePricingMetaFields = array(
'outward_code',
'postal_town',
'postal_county',
'auto_1hr',
'auto_5hr',
'auto_10hr',
'auto_weekend_evening',
'manual_1hr',
'manual_5hr',
'manual_10hr',
'manual_weekend_evening'
);
// Loop over meta array and register each new value.
// example.com/wp-json/wp/v2/postcode_pricing_pt/POST-ID
for ($i = 0, $size = count($postcodePricingMetaFields); $i < $size; ++$i) {
// Register additional meta fields.
register_post_meta('postcode_pricing_pt', '_postcode_pricing_' . $postcodePricingMetaFields[$i], array(
'show_in_rest' => true,
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function () {
return current_user_can('edit_posts');
}
));
}
}