Step 1: Go to an Edit Post wp-admin page
e.g. /wp-admin/post.php?post=7&action=edit
Step 2:
In the Chrome JavaScript console create two variables postId
and endPoint
based on the post ID of the post you want to modify.
e.g.
var postId = 7;
var endPoint = '/wp-json/wp/v2/posts/' + postId;
Step 3:
Enter the following in the Google Chrome JavaScript console.
jQuery.ajax({
method: 'GET',
url: endPoint,
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
} );
You should get back all the information about that post (note: you may have to expand the JavaScript object in the console).
Write via WP REST API
Step 4:
jQuery.ajax({
method: 'POST',
data: {
id: postId,
title: 'My Custom Title Written with REST API'
},
url: endPoint,
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
} );
This fails with message “401 (Unauthorized)”. Because we are writing to WordPress we need to authenticate.
Step 5:
Because we are on an Edit Post wp-admin screen, WordPress has populated some helpful information in the global JavaScript object wpApiSettings
. Specifically, wpApiSettings.nonce
contains a nonce for just this purpose. By passing this nonce as the value for the X-WP-Nonce
header, we can authenticate.
jQuery.ajax({
method: 'POST',
data: {
id: postId,
title: 'My Custom Title Written with REST API'
},
beforeSend: function ( xhr ) {
// Set header 'X-WP-Nonce' for authentication.
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
url: endPoint,
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
} );
Leave a Reply