While developing our plugins we encounter the need of using the WordPress REST API more and more often, and we found that the new V2 API can be an enjoyable API to use.
We encourage you to read the full documentation of the V2 API to have the minimal understanding of this system.
The WordPress Codex also has a handbook about the REST API
The API Client
As a client(aka the entity which gets data from the API), you can always implement your own way of requesting data from API.
There are some recommendations based on the environment you want to use like:
- The wp-api script –– a Backbone collection of all endpoints supported in this API by default
- There is also a npm client client
- The old fashion
fetchif you feel modern) if you need a simply and very quick way of requesting a specific endpoint and process your response in a specific way
- The first recommendation is the WordPress function
wp_remote_post, learn this function well and make your own custom requests.
- There is a PHP client example which you can use a starter.
- Another PHP client example which has a full integration with the Oauth1
The response callback
While creating your own callback, you need to be careful at returning value.
It may be tempting to use the
wp_send_json_ since it is the standard way to end AJAX requests.But remember that this function ends in an
exit statement so in this case, the API system will not have the chance to run any other actions after that.
A better way to respond in callback is the function rest_ensure_response
For Admin dashboard features we recommend the use of the basic nonce authentication since it is simple to use.