Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Backbone-based JavaScript client for WP API

NotificationsYou must be signed in to change notification settings

xwp/wp-api-client-js

 
 

Repository files navigation

Summary

This library provides an interface for theWP REST API by providing Backbone Models and Collections for all endpoints in the API.

Using

Activate the WP-API plugin. Enqueue the script directly:

wp_enqueue_script('wp-api' );

or as a dependency for your script:

wp_enqueue_script('my_script','path/to/my/script',array('wp-api' ) );

The library parses the root endpoint (the 'Schema') and creates matching Backbone models and collections. You will now have two root objects available to you:wp.api.models andwp.api.collections.

The models and collections include:

Models: * Category * Comment * Media * Page * PageMeta * PageRevision * Post * PostMeta * PostRevision * Schema * Status * Tag * Taxonomy * Type * UserCollections: * Categories * Comments * Media * PageMeta * PageRevisions * Pages * Posts * Statuses * Tags * Taxonomies * Types * Users

You can use these endpoints as-is to read, update, create and delete items using standard Backbone methods (fetch, sync, save & destroy for models, sync for collections). You can also extend these objects to make them your own, and build your views on top of them.

Default values

Each model and collection includes a reference to its 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 the corresponding endpoint supports. For example, models created fromwp.api.models.Post have a methods array of:

["GET", "POST", "PUT", "PATCH", "DELETE"]

Accepted options

Each model and collection contains a list of options the corrosponding endpoint accepts (note that options are passed as the second parameter when creating models or collections), for example:

wp.api.collections.Posts.prototype.options * author * context * filter * order * orderby * page * per_page * search * status

Localizing the API Schema

The client will accept and use a localized schema as part of thewpApiSettings object. The Schema is currently not passed by default; instead the client makes an ajax request to the API to load the Schema, then caches it in the browser's session storage (if available). Activating the client-js plugin withSCRIPT_DEBUG enabled uses a localized Schema. Check theclient-js example or this branch whichattempts to only localize the schema once per client.

Waiting for the client to load

Client startup is asynchronous. If the api schema is localized, the client can start immediately; if not the client makes an ajax request to load the schema. The client exposes a load promise for provide a reliable wait to wait for client to be ready:

wp.api.loadPromise.done(function(){//... use the client here})

Model examples:

To create a post and edit its categories, make sure you are logged in, then:

// Create a new postvarpost=newwp.api.models.Post({title:'This is a test post'});post.save();// Load an existing postvarpost=newwp.api.models.Post({id:1});post.fetch();// Get a collection of the post's categories (returns a promise)// Uses _embedded data if available, in which case promise resolves immediately.post.getCategories().done(function(postCategories){// ... do something with the categories.// The new post has an single Category: Uncategorizedconsole.log(postCategories[0].name);// response -> "Uncategorized"});// Get a posts author User model.post.getAuthorUser().done(function(user){// ... do something with userconsole.log(user.get('name'));});// Get a posts featured image Media model.post.getFeaturedImage().done(function(image){// ... do something with imageconsole.log(image);});// Set the post categories.post.setCategories(['apples','oranges']);// Get all the categoriesvarallCategories=newwp.api.collections.Categories()allCategories.fetch();varappleCategory=allCategories.findWhere({slug:'apples'});// Add the category to the postCategories collection we previously fetched.appleCategory.set('parent_post',post.get('id'));// Use the POST method so Backbone will not PUT it even though it has an id.postCategories.create(appleCategory.toJSON(),{type:'POST'});// Remove the Uncategorized categorypostCategories.at(0).destroy();// Check the results - re-fetchpostCategories=post.getCategories();postCategories.at(0).get('name');// response -> "apples"

Collection examples:

to get the last 10 posts:

varpostsCollection=newwp.api.collections.Posts();postsCollection.fetch();

to get the last 25 posts:

postsCollection.fetch({data:{per_page:25}});

use filter to change the order & orderby options:

postsCollection.fetch({data:{'filter':{'orderby':'title','order':'ASC'}}});

All collections support pagination automatically, and you can get the next page of results usingmore:

postsCollection.more();

to get page 5 of a collection:

posts.fetch({data:{page:5}});

check if the collection has any more posts:

posts.hasMore();

Working With Revisions

You can access post or page revisions using the PostRevisions or PageRevisions collections or through the Post or Page collection.

For example, to get a collection of all revisions of post ID 1:

var revisions = new wp.api.collections.PostRevisions({}, { parent: 1 });

Revision collections can also be accessed via their parent's collection. This example makes 2 HTTP requests instead of one, but now the original post and its revisions are avaible:

var post = new wp.api.models.Post( { id: 1 } );post.fetch();post.getRevisions().done( function( revisions ){console.log( revisions );});

If you add custom endpoints to the api they will also become available as models/collections. For example, you will get new models and collections when youadd REST API support to your custom post type. Note: because the schema is stored in the user's session cache to avoid re-fetching, you may need to open a new tab to get a new read of the Schema.

Development

To develop, build and test this library, you must haveNode installed. For Windows users, simplydownload and install Node. For Mac users, we recommend installing Node usingHomebrew. Once Homebrew is installed, runbrew install node to install Node.js.

Installation

Clone this repository, and then execute the following commands within the checkout directory:

$ npm install

This will use Node's NPM package manager to install all the dependencies for building and testing this library. We useBower to manage client script dependencies, but Bower script installation is handled as part of thenpm install command.

Building

To update the compiled JavaScript files in thebuild/ directory after you've made changes, run the library'sbuild script with the npm command:

$ npm run build

This will useGrunt to check the source scripts injs/ for syntax errors, then concatenate and minify them to createthe minified wp-api.min.js file and a corresponding source map file.

Testing

You can run the unit tests for this library using Grunt:

$ npmtest

A note on Grunt

The custom "build" and "test" scripts defined in this library'spackage.json enable access to Grunt's functionality after a simplenpm install; however, these commands can also be run directly using Grunt itself. In order to gain access to thegrunt console command, you must globally install the Grunt command-line interface:

$ npm install -g grunt-cli

Oncegrunt-cli has been installed, you can run the build and test commands withgrunt andgrunt test, respectively, without having to invoke the scripts via NPM.

About

Backbone-based JavaScript client for WP API

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript96.6%
  • HTML2.4%
  • PHP1.0%

[8]ページ先頭

©2009-2025 Movatter.jp