Question

I am trying to follow the instruction in the Gutenberg Handbook to create a block that can change meta data of a post.

Though when I try to use the setAttributes function from props to save the new data it persisted on the page, but is not actually saved back to the database, as I believe the Handbook states it should if it's source is meta. I must be missing something, but I cannot find a resource to help.

php:

   $args = ...

   register_post_type('event', $args);

   register_meta('event', 'event_location', [
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string'
    ]);

javascript:

registerBlockType('my-plugin/event-location', {
  title: 'Event Location',
  category: 'widgets',

  attributes: {
    location: {
      type: 'string',
      source: 'meta',
      meta: 'event_location'
    }
  },

  edit ({ className, attributes, setAttributes }) {
    const { location } = attributes

    function updateContent (e) {
      setAttributes({ location: e.target.value })
    }

    return el(
      'p',
      { className: className },
      el(
        'input',
        { value: location, onChange: updateContent }
      )
    )
  },

  save () {
    return null
  }
})
Was it helpful?

Solution

Think I found the answer here. The first argument to register_meta is not post type but object_type, which is in my case should be post rather than taxonomy or comment. The function description, found here, states as of WordPress 4.9.2 the correct parameter is post. Once I switched it everything worked.

register_meta('post', 'event_location', [
    'show_in_rest' => true,
    'single' => true,
    'type' => 'string'
]);

Also, here is a Github issue related to the same problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top