Updating Post Meta with Backbone and the REST API

I'm getting started with a project that is making use of Backbone and the WP REST API, but I"m having a little trouble.

Using the built in API JS for models and collections allows me to pretty easily update a post title or content. All I have to do is call:

this.model.set({title: 'New Title'});
this.model.save();

And everything works really well. But for post meta, there doesn't appear to be an easy way to update an entry to the database. Does anyone know how to go about taking a post model in Backbone, and updating it's meta data?

Topic backbone plugin-json-api rest-api Wordpress

Category Web


Now you can use the models api as well:

var post = new wp.api.models.Post( { id: 1 } );
post.fetch();
post.setMeta('metaKey', 'metaValue');
// Or multiple metas at one time:
post.setMetas({metaKeyOne: 'metaValueOne', metaKeyTwo: 'metaValueTwo'});
post.save()

For this to work , the meta must be registered for REST API with register_post_meta and show_in_rest argument set to true. Here is an example:

add_action(
    'init',
    function() {
        register_post_meta('my_post_type', 'my_meta_key', ['show_in_rest' => true, 'single' => true]);
    }
);

var parentId = 96; // the post id
var metaData = new wp.api.collections.PostMeta('', {parent: parentId});
metaData.fetch()
  .done(function(data) {
    var someKey = data.findWhere({key: 'someKey'});
    someKey.set('value', 'newValue');

    someKey.save({parent: parentId});
  });

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.