I'm looking for a way to allow guest posts to be created on my website, without users having to log in. I would prefer to do this in a secure way, without a plugin if possible.
I've tried using the WP Rest API to create the post through a form on the website front end, using a nonce to authenticate. However, I got a 401 unauthorized error while creating this as a non logged in user.
Did some research and it does not seem like the REST API can be used to create posts when the user is not logged in.
I did come across mentions about wp_ajax_nopriv_(action), but I couldn't find any recent documentation that seemed reliable.
This is the most reliable documentation I found, and it seemed a little dated.
WordPress REST API - Allow anyone to POST
and
https://www.justinsilver.com/technology/wordpress/creating-ajax-functions-in-wordpress/
I'm including my code below.
createStory() {
var newStory = {
'title': $("#title").val(),
'content': $("#description").val(),
'excerpt': $("#excerpt").val(),
'name': $("#name").val(),
'location': $("#location").val(),
'status': 'draft' //needed to publish the post, otherwise it is saved as a draft
};
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', siteData.nonce);
},
url: siteData.root_url + '/wp-json/wp/v2/helpers-story/',
type: 'POST',
data: newStory,
success: (response) => {
console.log("New post created");
console.log(response);
},
error: (response) => {
console.log("Post creation failed");
console.log(response);
}
})
return false;
}
This is part of the response I received.
responseJSON: {code: "rest_cannot_create", message: "Sorry, you are not allowed to create posts as this user.", data: {…}}
responseText: "{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}