Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether request is WP REST API request?

What is the best way to check whether a request is an API request?

Note that the request might be a custom API request, which means it may be as follows:

mysite.com/wp-json/my_namespace/my_version/my_action

Obviously, I can check whether the API route wp-json, but there should be a built-in function to check that.

I need it to do some hooks such as

add_action('init', 'do_something_only_if_api_request');

function do_something_only_if_api_request()
{
   if ( ! wp_api_request() ) {
     return;
   }
   // do stuff
}
like image 543
Nizar Blond Avatar asked Dec 12 '16 12:12

Nizar Blond


People also ask

How do I know if WordPress REST API is enabled?

Is the WordPress REST API enabled? The best way to check is to visit this URL: https://yoursite.com/wp-json. If you see some information which seems related to your WordPress REST API, it works. If you see something, it means that, at least, your WordPress REST API is enabled.

Is WP rest?

The REST API is a developer-oriented feature of WordPress.

How do I get a WordPress API request?

Get an API key for the API. Create a Plugin for adding a widget to your WordPress site. Customize your plugin with your API key and specific information you want to display in the widget. Use the WordPress Admin Area to place the widget on your site where you want it within your theme.

Can WordPress call REST API?

In particular, the WordPress REST API enables you to connect your WordPress website with external applications. This means you can develop a mobile app using practically any programming language, and use the WP REST API to fetch data from WordPress.


1 Answers

You can check defined('REST_REQUEST'). This constant is defined as true in rest_api_loaded() (and not defined otherwise).

There was a discussion of WP Rest API developers about the introduction of a new function like is_rest_request(). In the end they went for this constant.

like image 76
Onno Avatar answered Oct 01 '22 13:10

Onno