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'});

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?


2 Answers 2

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

    someKey.save({parent: parentId});

Now you can use the models api as well:

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

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:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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