Menu

WordPress REST API – JavaScript & Backbone

May 29, 2017 - javascript, WordPress

Resources

Backbone JavaScript Client

Client enables all CRUD operations on the content in WP database.
Below two examples are shown – reading and creating a post.

Activate the WP-API plugin.

// functions.php    
wp_enqueue_script( 'wp-api' );
// or
wp_enqueue_script( 'my_script', get_theme_file_uri( 'my_script.js'), array( 'wp-api' ), '1.0', true );

Then add file my_script.js to your theme folder.

Use the plugin

// my_script.js
wp.api.loadPromise.done( function() {
     // Create a new post
var post = new wp.api.models.Post( { title: 'This is a test post' } );
post.save();

// Load an existing post
var post = new wp.api.models.Post( { id: 1 } );
post.fetch();
} )

The response

var postContent = {
      'title':  'Great post',
      'content': 'To be written',
      'status': 'publish'
    };

    // send post content to WP
    var post = new wp.api.models.Post( postContent );
    var response = post.save();
    console.log(response);

post.save(); gives elaborate response:

"{"id":18,"date":"2017-05-29T20:19:24","date_gmt":"2017-05-29T20:19:24","guid":{"rendered":"http:\/\/localhost\/wprestapi\/254356-2\/","raw":"http:\/\/localhost\/wprestapi\/254356-2\/"},"modified":"2017-05-29T20:19:24","modified_gmt":"2017-05-29T20:19:24","password":"","slug":"254356-2","status":"publish","type":"post","link":"http:\/\/localhost\/wprestapi\/254356-2\/","title":{"raw":"254356","rendered":"254356"},"content":{"raw":"sdsad","rendered":"<p>sdsad<\/p>\n","protected":false},"excerpt":{"raw":"","rendered":"<p>sdsad<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/posts\/18"}],"collection":[{"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/comments?post=18"}],"version-history":[{"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/posts\/18\/revisions"}],"wp:attachment":[{"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/media?parent=18"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/categories?post=18"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/localhost\/wprestapi\/wp-json\/wp\/v2\/tags?post=18"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}"