WP-API JavaScript Client (Backbone.js)
The REST API has a JavaScript client that allows for convenient communication with the site. The library contains Models and Collections for all WP endpoints described in the section WP Routes Out of the Box, as well as for all manually created endpoints.
Backbone JavaScript Client (developer.wordpress.org).
Usage
To enable the WP API library, you need to enqueue the script wp-api
.
This can be done directly:
wp_enqueue_script( 'wp-api' );
or through a dependency on our script, for example, my_script:
wp_enqueue_script( 'my_script', 'path/to/my/script', array('wp-api') );
The wp-api script includes (depends on the following scripts):
'jquery', 'backbone', 'underscore', 'wp-api-request'
The library analyzes the root endpoint (REST API schema) and creates Backbone models and collections based on it. Thus, we have two main objects: wp.api.models and wp.api.collections, which contain the following JS methods:
// Models: wp.api.models.Category wp.api.models.Comment wp.api.models.Media wp.api.models.Page wp.api.models.PageMeta wp.api.models.PageRevision wp.api.models.Post wp.api.models.PostMeta wp.api.models.PostRevision wp.api.models.Schema wp.api.models.Status wp.api.models.Tag wp.api.models.Taxonomy wp.api.models.Type wp.api.models.User // Collections: wp.api.collections.Categories wp.api.collections.Comments wp.api.collections.Media wp.api.collections.PageMeta wp.api.collections.PageRevisions wp.api.collections.Pages wp.api.collections.Posts wp.api.collections.Statuses wp.api.collections.Tags wp.api.collections.Taxonomies wp.api.collections.Types wp.api.collections.Users
We can use these objects (endpoints) for reading/updating/creating/deleting items using standard methods (fetch, sync, save, and destroy for models, sync for collections).
For a complete list of methods and properties, see the code of the script wp-includes/js/wp-api.js.
Default Values
Each Model and Collection contains a reference to default values, for example:
wp.api.models.Post.prototype.args author : null comment_status : null content : null date : null date_gmt : null excerpt : null featured_image : null format : null modified : null modified_gmt : null password : null ping_status : null slug : null status : null sticky : null title : null
Available Methods
Each Model and Collection contains a list of methods supported by the corresponding endpoint. For example, the model wp.api.models.Post has the following methods:
["GET", "POST", "PUT", "PATCH", "DELETE"]
Accepted Parameters
Each Model and Collection contains a list of parameters accepted by the corresponding endpoint (note that parameters are passed as the second argument when creating models or collections), for example:
wp.api.collections.Posts.prototype.options // contains: author context filter order orderby page per_page search status
Examples of Using Models
To create/update a post, ensure you are authenticated and have sufficient permissions.
// Create a new post var post = new wp.api.models.Post( { title: 'This is a test post' } ); post.save();
Example of working with a post:
// Get post ID=1 var post = new wp.api.models.Post( { id: 1 } ); post.fetch(); // Get the collection of post categories (returns a promise). // Uses _embedded data (if available), in this case the promise resolves immediately. post.getCategories().done( function( postCategories ) { // ... do something with the categories // the new post has only one category: Uncategorized console.log( postCategories[0].name ); // will output "Uncategorized" } ); // Get the author of the post (User model) post.getAuthorUser().done( function( user ){ // ... do something with users console.log( user.get( "name" ) ); } ); // Get the image of the post (Media model). post.getFeaturedMedia().done( function( image ){ // ... do something with the image console.log( image ); } ); // Set the categories of the post post.setCategories( [ "apples", "oranges" ] );
Example of working with categories:
// Get all categories var allCategories = new wp.api.collections.Categories() allCategories.fetch(); // Find the category apples var appleCategory = allCategories.findWhere( { slug: "apples" } ); // Add the above post to the "apples" category (set the category for the post) appleCategory.set( "parent_post", post.get( "id" ) );
Examples of Using Collections
Get the 10 latest posts:
var postsCollection = new wp.api.collections.Posts(); postsCollection.fetch();
Get the 25 latest posts:
postsCollection.fetch( { data: { per_page: 25 } } );
Use a filter to change sorting parameters (order and orderby):
postsCollection.fetch( { data: { 'filter': { 'orderby': 'title', 'order': 'ASC' } } } );
All collections support pagination automatically, and the next batch of results can be obtained using the more() method:
postsCollection.more();
Get page 5 from the collection:
posts.fetch( { data: { page: 5 } } );
Check if there are more posts in the collection:
posts.hasMore();
Waiting for the wp-api Client (Script) to Load
Backbone.js loads asynchronously. If the API schema is localized and there is no need to make an AJAX request to retrieve the schema, the client starts working immediately. However, when you need to wait for the client to be fully ready, you should use loadPromise.done:
wp.api.loadPromise.done( function() { // Here you can use the client } )
Working with Revisions
Through the PostRevisions or PageRevisions collections, you can get all revisions of posts/pages. Or revisions can be obtained from the Post or Page collections.
For example, get all revisions of post 1:
var revisions = new wp.api.collections.PostRevisions({}, { parent: 1 });
Revision collections can also be accessed through the parent collection. In this example, two HTTP requests are performed instead of one, but now the original post and its revisions are available:
var post = new wp.api.models.Post( { id: 1 } ); post.fetch(); post.getRevisions().done( function( revisions ){ console.log( revisions ); });
If custom endpoints have been added to the API, they also become available as models/collections. For example, you will get new models and collections when adding REST API support to a custom Post Type.
Note: since the schema is cached in the user's session, to avoid reloading, you may need to open a new tab to get a new read of the schema.