So, I have a php page in wordpress (WP-Api 2):
<?php
/**
* Template Name: WP-Api
*/
add_action("wp_enqueue_scripts", "enqueue_");
function enqueue_() {
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
}
get_header(); ?>
<h1>oi</h1>
<script type="text/javascript">
jQuery.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
</script>
I want to run this example but the console says
Uncaught ReferenceError: wpApiSettings is not defined
What am I doing wrong? Thank you!
Take a look at the example here: https://codex.wordpress.org/Function_Reference/wp_localize_script
You need to wp_register_script and wp_enqueue_script or the JS variable will not be created.
Add the following code to functions.php and check if the user already logged in has the capabilities to POST (Create Products, Posting, Upload Media File, etc.)