使用新的EntityProvider API保存发布元数据

时间:2020-12-02 作者:Luis Martins

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 个回复
SO网友:Julio Braña Bouza

我认为onChange函数需要传递值,比如onChange={(value) => updateUrl(value)}

SO网友:Lovor

我做得很晚,但我认为这里的问题是你自定义帖子类型的注册码ebook (你没有显示)你失踪了supports 对于custom-fields 在args数组中:

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

\'show_in_rest\'          => true

相关推荐