wp_is_json_request()
Checks if the current request is a JSON request or expects a JSON response.
The following conditions are checked:
false !== strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) // or 'application/json' === $_SERVER['CONTENT_TYPE']
1 time — 0.000001 sec (speed of light) | 50000 times — 0.02 sec (speed of light) | PHP 7.2.5, WP 5.0
No Hooks.
Returns
true|false.
true— when the request expects a JSON response ($_SERVER['HTTP_ACCEPT']or$_SERVER['CONTENT_TYPE']containapplication/json).false— in other cases.
Usage
wp_is_json_request();
Examples
#1 Return JSON data when the query waits for it
$data = [ 'foo'=>'bar' ];
if( wp_is_json_request() ){
echo json_encode( $data );
}
else {
echo serialize( $data );
}
Changelog
| Since 5.0.0 | Introduced. |
wp_is_json_request() wp is json request code WP 6.9.1
function wp_is_json_request() {
if ( isset( $_SERVER['HTTP_ACCEPT'] ) && wp_is_json_media_type( $_SERVER['HTTP_ACCEPT'] ) ) {
return true;
}
if ( isset( $_SERVER['CONTENT_TYPE'] ) && wp_is_json_media_type( $_SERVER['CONTENT_TYPE'] ) ) {
return true;
}
return false;
}