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

该库通过为 API Schema 暴露的所有端点提供 Backbone Models 和 Collections,为 WP REST API 提供接口。

使用

激活 WP-API 插件。直接加载脚本:

wp_enqueue_script( 'wp-api' );

或者将其作为您脚本的依赖项:

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

该库解析根端点(即"Schema")并创建匹配的 Backbone models 和 collections。现在您将有两个根对象可用:wp.api.models 和 wp.api.collections。

Models 和 Collections 包括:

Models:
* 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 方法(models 的 fetch、sync、save & destroy,collections 的 sync)来读取、更新、创建和删除项目。您还可以扩展这些对象以使其成为您自己的,并在其上构建您的视图。

默认值

每个 model 和 collection 都包含对其默认值的引用,例如:

wp.api.models.Post.prototype.args

  • author: null
  • comment_status: null
  • content: null
  • date: null
  • date_gmt: null
  • excerpt: null
  • featured_media: null
  • format: null
  • modified: null
  • modified_gmt: null
  • password: null
  • ping_status: null
  • slug: null
  • status: null
  • sticky: null
  • title: null

可用方法

每个 model 和 collection 包含对应端点支持的方法列表。例如,从 wp.api.models.Post 创建的 models 具有如下 methods 数组:

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

接受的选项

每个 model 和 collection 包含对应端点接受的选项列表(注意:创建 models 或 collections 时,选项作为第二个参数传递),例如:

wp.api.collections.Posts.prototype.options

  • author
  • context
  • filter
  • order
  • orderby
  • page
  • per_page
  • search
  • status

本地化 API Schema

客户端将接受并使用作为 wpApiSettings 对象一部分的本地化 schema。目前 Schema 默认不传递;相反,客户端会向 API 发出 ajax 请求以加载 Schema,然后将其缓存在浏览器的 session storage 中(如果可用)。启用 SCRIPT_DEBUG 激活 client-js 插件将使用本地化的 Schema。查看 client-js 示例 或这个分支,它尝试仅为每个客户端本地化一次 schema。

等待客户端加载

客户端启动是异步的。如果 api schema 已本地化,客户端可以立即启动;否则,客户端会发出 ajax 请求以加载 schema。客户端公开了一个 load promise,以便可靠地等待客户端就绪:

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

Model 示例:

要创建一篇文章并编辑其分类,请确保已登录,然后执行以下操作:

// 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.getFeaturedMedia().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"

Collection 示例:

获取最后 10 篇文章:

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

获取最后 25 篇文章:

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

使用 filter 更改 order 和 orderby 选项:

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

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

postsCollection.more();

获取集合的第 5 页:

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

检查集合是否还有更多文章:

posts.hasMore();

处理修订版

您可以通过 PostRevisions 或 PageRevisions collections 或通过 Post 或 Page collection 访问文章或页面修订版。

例如,获取 ID 为 1 的文章的所有修订版集合:

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

修订版 collections 也可以通过其父级 collection 访问。此示例执行 2 次 HTTP 请求而不是 1 次,但现在原始文章及其修订版均可用:

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

如果您向 API 添加了自定义端点,它们也将作为 models/collections 可用。例如,当您 为您的自定义文章类型添加 REST API 支持 时,您将获得新的 models 和 collections。要访问创建的自定义端点,请使用项目的 JSON 端点名称作为 CamelCase;例如,如果项目在 JSON 路径 /wp-json/wp/v2/my-custom-post 处找到,则可以通过 api wp.api.collections.MyCustomPost 访问。注意:由于 schema 存储在用户的 session cache 中以避免重新获取,您可能需要打开新标签页才能重新读取 Schema。

// Extend wp.api.models.Post and wp.api.collections.Posts to load a custom post type
const CustomPost = wp.api.models.Post.extend( {
  urlRoot: wpApiSettings.root + 'wp/v2/custom_post_slug',
  defaults: {
    type: 'custom_post_slug',
  },
} );
const CustomPosts = wp.api.collections.Posts.extend( {
  url: wpApiSettings.root + 'wp/v2/custom_post_slug',
  model: BLProduct,
} );
const someCustomPosts = new CustomPosts();
someCustomPosts.fetch().then( ( posts ) => {
  // do something with the custom posts
} );