REST API 文档

💡 云策文档标注

概述

WordPress REST API 提供了一系列全局参数(也称为“元参数”),用于控制请求/响应的处理方式,这些参数适用于所有资源,位于实际资源层之上。

关键要点

  • _fields 参数:允许指定响应中返回的字段子集,以减少数据量和提高性能,支持嵌套属性。
  • _embed 参数:启用嵌入模式,在响应中包含相关资源,减少 HTTP 请求,可指定嵌入的链接关系。
  • _method 参数或 X-HTTP-Method-Override 头:用于覆盖 HTTP 方法,确保与不支持某些方法的服务器或客户端兼容。
  • _envelope 参数:启用信封模式,将完整响应数据(包括状态码和头信息)封装在响应体中,以应对代理或客户端限制。
  • _jsonp 参数:支持 JSONP 响应,允许跨域请求,适用于旧版浏览器。

代码示例

// 使用 _fields 参数限制返回字段
/wp/v2/posts?_fields=author,id,excerpt,title,link

// 使用 _embed 参数嵌入特定资源
/wp/v2/posts?_embed=author,wp:term

// 使用 _method 参数覆盖 HTTP 方法
POST /wp-json/wp/v2/posts/42?_method=DELETE

// 使用 _envelope 参数获取信封响应
GET /wp/v2/users/me?_envelope

// 使用 _jsonp 参数进行 JSONP 回调
<script src="https://example.com/wp-json/?_jsonp=receiveData"></script>

注意事项

  • 使用 _fields 参数时,应精心设计查询以仅请求必要属性,提升应用性能。
  • _embed 参数与 _fields 参数结合使用时,需在字段中包含 _links 和 _embedded。
  • _method 参数或 X-HTTP-Method-Override 头应仅用于 POST 请求,避免 GET 请求被错误缓存。
  • _envelope 参数主要用于兼容性场景,未来应避免传递除“1”外的其他值。
  • _jsonp 参数的回调函数名只能包含字母数字、下划线或点号,否则会返回 HTTP 400 错误。

📄 原文内容

The API includes a number of global parameters (also called “meta-parameters”) which control how the API handles the request/response handling. These operate at a layer above the actual resources themselves, and are available on all resources.

_fields

A REST resource like a Post contains a large quantity of data: basic information such as content, title, and author ID, but also registered metadata and fields, media information, and links to other resources. Your application may not need all of this information on every request.

To instruct WordPress to return only a subset of the fields in a response, you may use the _fields query parameter. If for example you are building an archive view and only need the ID, title, permalink, author and excerpt for a collection of posts, you can restrict the response to only those properties with this fields query:

/wp/v2/posts?_fields=author,id,excerpt,title,link

You may alternatively provide that same list using query parameter array syntax instead of a comma-separated list:

/wp/v2/posts?_fields[]=author&_fields[]=id&_fields[]=excerpt&_fields[]=title&_fields[]=link

When _fields is provided then WordPress will skip unneeded fields when generating your response object, avoiding potentially expensive internal computation or queries for data you don’t need. This also means the JSON object returned from the REST API will be smaller, requiring less time to download and less time to parse on your client device.

Carefully design your queries to pull in only the needed properties from each resource to make your application faster to use and more efficient to run.

As of WordPress 5.3 the _fields parameter supports nested properties. This can be useful if you have registered many meta keys, permitting you to request the value for only one of the registered meta properties:

?_fields=meta.one-of-many-keys

Only the meta value with the key one-of-many-keys will be returned, and others will be excluded.

You can also request specific deeply-nested properties within a complex meta object:

?_fields=meta.key_name.nested_prop.deeply_nested_prop,meta.key_name.other_nested_prop

_embed

Most resources include links to related resources. For example, a post can link to the parent post, or to comments on the post. To reduce the number of HTTP requests required, clients may wish to fetch a resource as well as the linked resources. The _embed parameter indicates to the server that the response should include these embedded resources.

Embed mode is enabled if the _embed parameter is passed in the query string (GET parameter). This parameter does not require a value (i.e. ?_embed is valid), however can be passed “1” as a value if required by a client library.

As of WordPress 5.4, the resources to embed can be limited by passing a list of link relation names to the _embed parameter. For example, /wp/v2/posts?_embed=author,wp:term will only embed the post’s author and the lists of terms associated with the post.

Resources in embed mode will contain an additional _embedded key next to the _links key containing the linked resources. Only links with the embeddable parameter set to true will be embedded.

In order to use _embed together with _fields, add _embedded as well as _links to the fields, for instance, /wp-json/wp/v2/posts/_embed=author,wp:term&_fields=title,author,_links,_embedded.

For more about linking and embedding, see the Linking and Embedding page.

_method (or X-HTTP-Method-Override header)

Some servers and clients cannot correctly process some HTTP methods that the API makes use of. For example, all deletion requests on resources use the DELETE method, but some clients do not provide the ability to send this method.

To ensure compatibility with these servers and clients, the API supports a method override. This can be passed either via a _method parameter or the X-HTTP-Method-Override header, with the value set to the HTTP method to use.

Clients should only ever send a method override parameter or header with POST requests. Using the method override with GET requests may cause the request to be incorrectly cached.

A POST to /wp-json/wp/v2/posts/42?_method=DELETE would be translated to a DELETE to the wp/v2/posts/42 route.

Similarly, the following POST request would become a DELETE:

POST /wp-json/wp/v2/posts/42 HTTP/1.1
Host: example.com
X-HTTP-Method-Override: DELETE

_envelope

Similarly to _method, some servers, clients, and proxies do not support accessing the full response data. The API supports passing an _envelope parameter, which sends all response data in the body, including headers and status code.

Envelope mode is enabled if the _envelope parameter is passed in the query string (GET parameter). This parameter does not require a value (i.e. ?_envelope is valid), but can be passed “1” as a value if required by a client library.

For future compatibility, other values should not be passed.

Enveloped responses include a “fake” HTTP 200 response code with no additional headers (apart from Content-Type) that should ensure the response correctly passes through intermediaries.

For example, given the following response to a GET to wp/v2/users/me:

HTTP/1.1 302 Found
Location: http://example.com/wp-json/wp/v2/users/42

{
  "id": 42,
  ...
}

The equivalent enveloped response (with a GET to wp/v2/users/me?_envelope) would be:

HTTP/1.1 200 OK

{
  "status": 302,
  "headers": {
    "Location": "http://example.com/wp-json/wp/v2/users/42"
  },
  "body": {
    "id": 42
  }
}

_jsonp

The API natively supports JSONP responses to allow cross-domain requests for legacy browsers and clients. This parameter takes a JavaScript callback function which will be prepended to the data. This URL can then be loaded via a <script> tag.

The callback function can contain any alphanumeric, _ (underscore), or . (period) character. Callbacks which contain invalid characters will receive a HTTP 400 error response, and the callback will not be called.

Modern browsers can use Cross-Origin Resource Sharing (CORS) preflight requests for cross-domain requests, but JSONP can be used to ensure support with all browsers.

For example:

<script>
function receiveData( data ) {
  // Do something with the data here.
  // For demonstration purposes, we'll simply log it.
  console.log( data );
}
</script>
<script src="https://example.com/wp-json/?_jsonp=receiveData"></script>