1

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?

3

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

0

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/

8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.