Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wp-api cookie authentication wpApiSettings is not defined

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 );
    }
});
like image 305
Tom Avatar asked Oct 27 '25 11:10

Tom


1 Answers

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');
like image 108
Benjamín Sierra Avatar answered Oct 29 '25 05:10

Benjamín Sierra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!