Skip to content

NickNaso/client-js

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 

Repository files navigation

Backbone.js App for WP REST API

This library provides a client-side interface for the WP REST API plugin for WordPress. This code in this repository generates the Backbone JavaScript application that pairs with WP REST API. Using this library, you can interact with WordPress installations that have WP REST API installed using Backbone Models and Collections. Learn more about Backbone here.

Usage

Setup

The compiled JavaScript wp-api.js file is included with the WP REST API by default. If you want to use it, simply make your script depend on wp-api when you enqueue it. If you want to enqueue the script manually, add wp_enqueue_script( 'wp-api' ) to a callback on wp_enqueue_scripts.

That being said, this repository is setup as a WordPress plugin for development purposes. You can activate this plugin along side WP REST API, and they will play nice together. The Client JS will dequeue the API version of the code and enqueue it's own.

Examples

The Backbone library supplies you with some Backbone models and collections for each route in the WP REST API. A model represents a single object such as a post. A collection represents a group of objects. We can use a model to pull a specific post from a WordPress installation:

var post = new wp.api.models.Post( { ID: 1 } ); post.fetch().done( function() { // post.attributes contain the attributes of the post console.log( post.attributes ); });

We can also grab a collection of posts:

var posts = new wp.api.collections.Posts(); posts.fetch().done( function() { posts.each( function( post ) { // post.attributes contain the attributes of the post console.log( post.attributes ); }); });

Requests are broken up into pages based on how posts_per_page is set or filtered. Therefore, sometimes we need to paginate through a collection:

var posts = new wp.api.collections.Posts(); posts.fetch().done( function() { posts.each( function( post ) { // post.attributes contain the attributes of the post console.log( post.attributes ); }); if ( posts.hasMore() ) { posts.more().done( function() { posts.each( function( post ) { // post.attributes contain the attributes of the post console.log( post.attributes ); }); }); } });

About

Backbone-based Javascript client for WP API

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 96.4%
  • PHP 3.6%