1

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!

dehq
  • 449
  • 5
  • 12

2 Answers2

2

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.

JB belcherj
  • 171
  • 7
0

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.)

/*Cookies Authentication*/
 
     wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
     wp_enqueue_script('wp-api');
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '22 at 21:02