wp_doing_ajax()
云策文档标注
概述
wp_doing_ajax() 函数用于判断当前请求是否为 WordPress Ajax 请求,返回布尔值。它基于 DOING_AJAX 常量定义,并可通过过滤器 wp_doing_ajax 进行自定义。
关键要点
- 函数返回 true 表示当前是 WordPress Ajax 请求,否则返回 false。
- 内部实现依赖于 DOING_AJAX 常量,并通过 apply_filters('wp_doing_ajax', ...) 允许开发者过滤结果。
- 常用于在代码中区分 Ajax 请求和普通请求,以调整输出行为,例如使用 wp_send_json_success() 或直接返回数据。
代码示例
function wpdocs_render() {
/* ........ SOME LOGIC ....... */
$return_data = array( 'success' => true );
if ( wp_doing_ajax() ) {
wp_send_json_success( $return_data );
} else {
return $return_data;
}
}
原文内容
Determines whether the current request is a WordPress Ajax request.
Source
function wp_doing_ajax() {
/**
* Filters whether the current request is a WordPress Ajax request.
*
* @since 4.7.0
*
* @param bool $wp_doing_ajax Whether the current request is a WordPress Ajax request.
*/
return apply_filters( 'wp_doing_ajax', defined( 'DOING_AJAX' ) && DOING_AJAX );
}
Hooks
- apply_filters( ‘wp_doing_ajax’, bool $wp_doing_ajax )
-
Filters whether the current request is a WordPress Ajax request.
Changelog
| Version | Description |
|---|---|
| 4.7.0 | Introduced. |
Skip to note 2 content
Ashwin Parthasarathi
In a PHP code, if we want to differentiate its output behavior based on how it is being called (like a normal function or like a WP AJAX callback), then we should use the wp_doing_ajax() function like below,
function wpdocs_render() { /* ........ SOME LOGIC ....... */ $return_data = array( 'success' => true ); if ( wp_doing_ajax() ) { wp_send_json_success( $return_data ); } else { return $return_data; } }