函数文档

wp_is_serving_rest_request()

💡 云策文档标注

概述

wp_is_serving_rest_request() 函数用于检测 WordPress 当前是否正在处理 REST API 请求。它基于全局常量 'REST_REQUEST' 进行判断,仅在实际 REST 请求时返回 true。

关键要点

  • 函数依赖 'REST_REQUEST' 全局常量,仅在真实 REST 请求时返回 true,不适用于预加载 REST 响应等场景。
  • 调用时机需在 'parse_request' 动作之后,因为常量在此后才定义。
  • 返回布尔值:true 表示当前为 REST API 请求,false 表示不是。
  • 相关函数 wp_is_rest_endpoint() 可用于检查 REST 端点处理。

代码示例

function wp_is_serving_rest_request() {
    return defined( 'REST_REQUEST' ) && REST_REQUEST;
}

注意事项

  • 不要过早调用此函数,确保在 'parse_request' 动作后使用以避免常量未定义错误。
  • 适用于无头 WordPress 或安全功能(如 OTP 验证)中区分 REST 请求。

📄 原文内容

Determines whether WordPress is currently serving a REST API request.

Description

The function relies on the ‘REST_REQUEST’ global. As such, it only returns true when an actual REST request is being made. It does not return true when a REST endpoint is hit as part of another request, e.g. for preloading a REST response. See wp_is_rest_endpoint() for that purpose.

This function should not be called until the ‘parse_request’ action, as the constant is only defined then, even for an actual REST request.

Return

bool True if it’s a WordPress REST API request, false otherwise.

Source

function wp_is_serving_rest_request() {
	return defined( 'REST_REQUEST' ) && REST_REQUEST;
}

Changelog

Version Description
6.5.0 Introduced.

User Contributed Notes