Many times I have code and I want to make sure it only runs in a rest api context, or it never runs in a rest context.
I know there are some hooks, but is there a function similar to wp_is_doing_cron
?
I would use :
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {...}
Source: https://github.com/WP-API/WP-API/issues/926#issuecomment-162920686
If you take a look to this source code on you will notice the constant is defined before processing anything, I would check for it instead of calling the mentioned function wp_is_json_request()
Why?
if headers were not set when you do the check, it will return false, here is a real example reported for a GET request: https://github.com/WordPress/gutenberg/issues/11327
Yes, wp_is_json_request()
can be used to determine if the current request is a REST API request
Checks whether current request is a JSON request, or is expecting a JSON response.
Official docs: https://developer.wordpress.org/reference/functions/wp_is_json_request/
if ( defined( 'JSON_REQUEST' ) && JSON_REQUEST )
Source: github.com/WP-API/WP-API/issues/926#issuecomment-162920686
REST_REQUEST
and not JSON_REQUEST
.