The WordPress REST API has become the go-to for any communication between the front-end and back-end. We’ve come a long way, from using admin-ajax to a professional, flexible and extendible REST API.
Registering routes
Registering a REST endpoint is pretty easy, below you’ll find some ready-to-use code, including the plugin headers.
<?php
/**
* Plugin Name: Register REST Route Example
*/
add_action( 'rest_api_init', function() {
// Register route for GET: example.com/wp-json/example/v1/action
register_rest_route( 'example/v1', '/action', array(
'methods' => 'GET',
'callback' => function($request) {
return $request->get_params();
},
'permission_callback' => function () {
return current_user_can( 'manage_options' );
}
));
});
This is everything you need to register a new endpoint in the REST API. The example above returns the parameters that you send as an example, so you can experiment and see what data our REST endpoint is receiving.
The front-end part
We can send data to this endpoint with a fetch or ajax call in javascript.
Example with Fetch
fetch('https://example.com/wp-json/example/v1/action?param1=test¶m2=test2')
.then(response => response.json())
.then(data => console.log(data));
Example with jQuery ajax’s method.
jQuery.ajax({
url: ''https://example.com/wp-json/example/v1/action?param1=test¶m2=test2',
method: 'GET'
}, function(data, status){
console.log(data);
});
This should show us an array containing param1 and param2 in the console.
User authentication using the WordPress REST API
When it’s about user authentication, it’s handy to include the ‘wp-api’ dependency when enqueueing your script;
wp_enqueue_script('your-script', 'path_to_your_script', array('wp-api'));
This gives access to the wpApiSettings variable in javascript, allowing you to access the user nonce:
console.log(wpApiSettings.nonce);
This means we can send the nonce to our REST API endpoint and use that to authenticate the user.
An example of communicating with the REST API with an authenticated user using the WP Nonce with fetch:
fetch('https://example.com/wp-json/example/v1/action?param1=test¶m2=test2', {
method: 'GET',
headers: {
'X-WP-Nonce': wpApiSettings.nonce
}
})
.then(response => response.json())
.then(data => console.log(data));
An example of communicating with the REST API with an authenticated user using the WP Nonce with jQuery ajax:
jQuery.ajax({
url: 'https://example.com/wp-json/example/v1/action?param1=test¶m2=test2',
method: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
}
}, function(data, status){
console.log(data);
});
That’s it! You can basically go anywhere from here, ex: converting the GET requests to POST requests.
More info on REST endpoints: https://developer.wordpress.org/reference/functions/register_rest_route/
Leave a Reply