最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Detect if REST API is running

programmeradmin6浏览0评论

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?

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?

Share Improve this question asked Jan 21, 2019 at 21:13 Tom J NowellTom J Nowell 61k7 gold badges79 silver badges148 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 4

I would use :

if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {...}

Source: https://github/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/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/reference/functions/wp_is_json_request/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论