WordPress中文开发手册

  1. Home
  2. Docs
  3. WordPress中文开发手册
  4. WordPress REST API手册
  5. 使用REST API
  6. 骨干JavaScript客户端

骨干JavaScript客户端

REST API包含一个JavaScript / Backbone客户端库。

该库为WP REST API提供了一个界面,为所有展现API模式的端点提供了骨干模型和集合。

##使用

激活WP-API插件。 直接排队脚本:

wp_enqueue_script( 'wp-api' );

或作为脚本的依赖:

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

库解析根端点(“Schema”)并创建匹配的Backbone模型和集合。 你现在可以有两个根对象:wp.api.modelswp.api.collections

模型和收藏包括:

模型:

  • Category
  • Comment
  • Media
  • Page
  • PageMeta
  • PageRevision
  • Post
  • PostMeta
  • PostRevision
  • Schema
  • Status
  • Tag
  • Taxonomy
  • Type
  • User

Collections:

  • Categories
  • Comments
  • Media
  • PageMeta
  • PageRevisions
  • Pages
  • Posts
  • Statuses
  • Tags
  • Taxonomies
  • Types
  • Users

您可以使用这些端点来使用标准的Backbone方法来读取,更新,创建和删除项目(获取,同步,保存和销毁模型,同步收集)。 您还可以扩展这些对象,使其成为您自己的,并在其上构建您的视图。

Default values

每个模型和集合都包含对其默认值的引用,例如:

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

可用的方法

每个模型和集合都包含相应端点支持的方法列表。 例如,从wp.api.models.Post创建的模型有一个方法数组:

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

接受的选项

每个模型和集合包含相应端点接受的选项列表(注意,在创建模型或集合时,选项作为第二个参数传递),例如:

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

本地化API模式

客户端将接受并使用本地化模式作为“wpApiSettings”对象的一部分。 默认情况下,模式目前不会传递; 而是客户端向API加载ajax请求以加载模式,然后将其缓存到浏览器的会话存储中(如果可用)。 启用启用了“SCRIPT_DEBUG”的client-js插件使用本地化的模式。 检查[client-js示例](https://github.com/WP-API/client-js/blob/master/client-js.php)或者这个分支,它试图只将每个客户端的模式本地化一次。 (https://github.com/WP-API/client-js/compare/features/only-localize-schma-once?expand=1)。

等待客户端加载

客户端启动是异步的。 如果api模式是本地化的,客户端可以立即启动; 如果客户端不是ajax请求来加载模式。 客户端公开了一个负担承诺,提供可靠的等待,等待客户端准备好:

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

模型示例:

要创建一个帖子并修改其类别,请确保您已登录,然后:

// 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();
 
// 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: Uncategorized
console.log( postCategories[0].name );
// response -> "Uncategorized"
} );
 
// Get a posts author User model.
post.getAuthorUser().done( function( user ){
// ... do something with user
console.log( user.get( 'name' ) );
} );
 
// Get a posts featured image Media model.
post.getFeaturedImage().done( function( image ){
// ... do something with image
console.log( image );
} );
 
// Set the post categories.
post.setCategories( [ 'apples', 'oranges' ] );
 
// Get all the categories
var allCategories = new wp.api.collections.Categories()
allCategories.fetch();
 
var appleCategory = 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 category
postCategories.at( 0 ).destroy();
 
// Check the results - re-fetch
postCategories = post.getCategories();
 
postCategories.at( 0 ).get( 'name' );
// response -> "apples"

集合示例:

得到最后10个帖子:

var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch();

获取最后25个帖子:

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

使用过滤器更改订单和orderby选项:

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

所有收藏都自动支持分页,您可以使用more获得下一页结果:

postsCollection.more();

获取一个集合的第5页:

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

检查收集是否有更多的帖子:

posts.hasMore();

使用修订

您可以使用PostRevisions或PageRevisions集合或通过Post或页面集合访问帖子或页面修订。

例如,要获取所有版本的帖子ID 1的集合:

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

修订集合也可以通过父母的收藏进行访问。 这个例子使得2个HTTP请求而不是一个HTTP请求,但现在可以使用原始帖子及其修订版本:

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

如果您将自定义端点添加到api,它们也将作为模型/集合使用。 例如,当您[为您的自定义帖子类型添加REST API支持](http://v2.wp-api.org/extending/custom-content-types/)时,您将获得新的模型和集合。 注意:由于模式存储在用户的会话缓存中以避免重新获取,因此您可能需要打开一个新的选项卡才能对Schema进行新的读取。