I have this script to add a new post to a website via API but I get wpApiSettings is not defined all the time.
This is how I enqueue a script in my functions.php:
function api_test() {
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
}
add_action( 'wp_enqueue_scripts', 'api_test' );
and this is how I try to insert the post:
jQuery.ajax({
url: wpApiSettings.root + '/wp-json/wp/v2/posts',
method: 'POST',
data: objData,
crossDomain: true,
contentType: 'application/json',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
success: function( data ) {
console.log( data );
},
error: function( error ) {
console.log( error );
}
});
Add this code in functions.php and check if the user has the capabilities to perform the action.
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
wp_enqueue_script('wp-api');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With