5

According to the announcement on the Make WordPress Core blog post it appears that to use post meta on a post things have changed quite a bit.

I'm trying to get a simple block to read and save data from a custom field, and for some reason each time I hit save the data is lost.

I start by registering the custom field in PHP (attached to the init hook):

  register_post_meta('ebook', 'main_video', array(
    'show_in_rest' => true,
    'single' => true,
    'type' => 'string',
  ));

and from the block controls I'm trying to then read and set methods to write into that field as follows:

const postType = useSelect((select) => select('core/editor').getCurrentPostType(), []);
  const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
  const url = meta && meta['main_video'];
  const updateUrl = (newValue) => {
    setMeta({ ...meta, main_video: newValue.url });
  };

Both url and updateUrl variables are then consumed by a gutenberg component:

<LinkControl 
   className="wp-block-navigation-link__inline-link-input" 
   value={{ url }} 
   onChange={updateUrl} 
   settings={[]} 
/>

If I log the values I can see data coming in and being updated, but as soon as I hit save on the post everything is reset.

The ebook post type where this custom field is being registered has support declared for custom-fields.

I've followed the official docs on this a few times and couldn't get it to work as they describe.

Am I missing a key step here or something's amiss?

2
  • Did you find solution to the problem ?
    – andrew
    May 11 at 0:52
  • At a glance, this all looks alright to me. Have you continued to experience this issue?
    – bosco
    Jun 11 at 20:20
0

I think your onChange function needs to pass the value, like onChange={(value) => updateUrl(value)}

0

I am very late at this, but I think the problem here was that at registration code for your custom post type ebook (which you did not show) you were missing supports for custom-fields in args array:

'supports'              => [ 'title', 'editor', 'custom-fields' ]

and also

'show_in_rest'          => true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.