WORDPRESS | Rest API authentication – Nonce
When working with REST API, before or later, you must work with authentication.
Right now there are three types available:
Cookie Authentication – For plugins/themes running on the same site
OAuth – For external clients
Basic Authentication – For testing only
We will use the first one: Cookie authentication.
First of all we create a “Nonce”, so open your function.php ( from your theme ) and add this code :
/***************************************** Cookies Authentication *****************************************/ wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) ); wp_enqueue_script('wp-api');
With this two line of code, we tell wordpress to create a “nonce“.
Now we need to create the .js side:
Open your .js file and
$.ajax( { url: wpApiSettings.root + 'wp/v2/posts/34', /* This is the end-point that refer to the posts with id 34 */ method: 'POST', /* The method can be " POST " or " GET " */ beforeSend: function ( xhr ) { /* The function that set the nonce */ xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); /* The XMLHttpRequest.setRequestHeader() method sets the value of an HTTP request header. */ }, data:{ 'title' : 'New Ticket Title' /* The new title of the post */ } } ).done( function ( response ) { /* The response */ console.log( response ); } );
That’s all if you reload one page of your site with the “console” open, you can see an answer like this one :
That’s mean that all it’s ok.
Now you can connect this action to something that trigger it.