TransWikia.com

Detect if REST API is running

WordPress Development Asked by Tom J Nowell on February 8, 2021

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?

2 Answers

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

Answered by Pabamato on February 8, 2021

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/

Answered by Tom J Nowell on February 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP