Saving Metadata from the Gutenberg Editor Sidebar to the Database

Your JavaScript code works for me. The metadata do get saved.

But perhaps you’d like to try my code which is pretty much completed, i.e. on page load, the checkbox is auto-checked/unchecked (and the text box is also shown/hidden) depending on the current database value. Secondly, I did it just as the Gutenberg team did it with the original component for the featured image and it’s actually easy.. I mean, I’m just hoping you can learn some good stuff from my code. 🙂

Nonetheless, regarding the question or getting your code to saving the metadata, one issue I noted before I posted the original answer, is the auth_callback for the _featured_image_is_video meta:

register_meta(
  'post',
  '_featured_image_is_video',
  array(
    ...
    // 'auth_callback' => function() {
    //     return current_user_can('edit_posts');
    // }
  )
);

Why did you comment out the auth_callback? Because if you do that, then it would default to __return_false() for protected meta (where the name begins with _/underscore), which means no one is allowed to edit the meta via the REST API! :p

So try un-commenting it out. But I’m not sure about that because if you actually had it commented in your actual code, then you would’ve noticed it since WordPress/Gutenberg would display a notice on the post editing screen saying the post could not be updated (because you have no permission to edit the meta or that the auth_callback always returns false).

To other readers:

Make sure your custom post type supports custom fields, because the REST API handbook says:

Note that for meta fields registered on custom post types, the post
type must have custom-fields support. Otherwise the meta fields will
not appear in the REST API.

And when the meta fields do not appear in the REST API, the meta fields will not be saved/updated via the REST API.

Leave a Comment