I am building an application on WordPress that requires a simple front end form where anyone can submit information that needs to be saved in the database. I am attempting to handle this through the REST API. (Due to the nature of the application, there can not be any redirection of the page when this information is submitted.)
I have no problem setting up the REST API (v2) so that I can submit a post. It works great when I am logged into WordPress. When I try to fill out the form when I am not logged in to WordPress, I receive an error.
Failed to load resource: the server responded with a status of 403 (Forbidden)
How can I set the API to receive a POST from anyone without authentication?
Here is my javascript:
$( '#post-submission-form' ).on( 'submit', function(e) {
e.preventDefault();
var title = $( '#post-submission-title' ).val();
var excerpt = $( '#post-submission-excerpt' ).val();
var content = $( '#post-submission-content' ).val();
var status = 'draft';
var data = {
title: title,
excerpt: excerpt,
content: content
};
$.ajax({
method: "POST",
url: POST_SUBMITTER.root + 'wp/v2/posts',
data: data,
beforeSend: function ( xhr ) {
//xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
});
Here is how I am initializing my javascript:
function holiday_scripts() {
// Onload JS
wp_enqueue_script( 'holiday-js', get_template_directory_uri() . '/js/holiday.js', array(), false, true );
//localize data for script
wp_localize_script( 'holiday-js', 'POST_SUBMITTER', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
'success' => __( 'Thanks for your submission!', 'your-text-domain' ),
'failure' => __( 'Your submission could not be processed.', 'your-text-domain' ),
'current_user_id' => 9
)
);
}
add_action( 'wp_enqueue_scripts', 'holiday_scripts' );
Does anyone have any idea on how to accomplish this?
Thanks!