wp_is_jsonp_request()
云策文档标注
概述
wp_is_jsonp_request() 函数用于检测当前请求是否为 JSONP 请求或期望 JSONP 响应。它通过检查 GET 参数和回调函数有效性来返回布尔值。
关键要点
- 函数返回布尔值:true 表示是 JSONP 请求,false 表示不是。
- 检查 $_GET['_jsonp'] 参数是否存在,若不存在则直接返回 false。
- 使用 wp_check_jsonp_callback() 验证回调函数名称的有效性。
- 通过 rest_jsonp_enabled 过滤器允许开发者控制 JSONP 是否启用。
- 该函数自 WordPress 5.2.0 版本引入。
代码示例
function wp_is_jsonp_request() {
if ( ! isset( $_GET['_jsonp'] ) ) {
return false;
}
if ( ! function_exists( 'wp_check_jsonp_callback' ) ) {
require_once ABSPATH . WPINC . '/functions.php';
}
$jsonp_callback = $_GET['_jsonp'];
if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
return false;
}
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
return $jsonp_enabled;
}注意事项
- JSONP 主要用于跨域请求,但需注意安全风险,如回调函数注入攻击。
- rest_jsonp_enabled 过滤器默认启用 JSONP,可通过返回 false 禁用。
- 相关函数包括 wp_check_jsonp_callback() 用于验证回调名称,apply_filters() 用于调用过滤器。
原文内容
Checks whether current request is a JSONP request, or is expecting a JSONP response.
Source
function wp_is_jsonp_request() {
if ( ! isset( $_GET['_jsonp'] ) ) {
return false;
}
if ( ! function_exists( 'wp_check_jsonp_callback' ) ) {
require_once ABSPATH . WPINC . '/functions.php';
}
$jsonp_callback = $_GET['_jsonp'];
if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
return false;
}
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
return $jsonp_enabled;
}
Hooks
- apply_filters( ‘rest_jsonp_enabled’, bool $jsonp_enabled )
-
Filters whether JSONP is enabled for the REST API.
Changelog
| Version | Description |
|---|---|
| 5.2.0 | Introduced. |