WordPress REST API – Permission Callbacks

The issue was because I wasn’t generating and sending a nonce value with the request. In order to generate a nonce value. Localize the value of a wp_create_nonce('wp_rest') function call.

wp_localize_script('application', 'api', array(
    'root' => esc_url_raw(rest_url()),
    'nonce' => wp_create_nonce('wp_rest')
));

This will then be accessible to the window object of the browser which can be accessed via Javascript, this nonce should then be passed as the value of the request header X-WP-Nonce when executing XHR / HTTP Requests. An example of which is as follows:

var request = new XMLHttpRequest();

request.addEventListener('load', function() {
    console.log(this.responseText);
}

request.open('GET', api.root + 'mynamespace/posts');

// You must set headers after the request has been opened and before itself.
request.setRequestHeader('X-WP-Nonce`, api.nonce);

request.send(); // will fire the event listener above when fulfilled.

I hope this was helpful.

Leave a Comment