未定义WP-API Cookie身份验证wpApiSettings

时间:2019-01-23 16:13:02

标签: wordpress wordpress-rest-api

我有这个脚本可以通过API向网站添加新帖子,但我一直都没有定义wpApiSettings。

这就是我将脚本放入我的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' );

这就是我尝试插入帖子的方式:

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 );
    }
});

1 个答案:

答案 0 :(得分:0)

就我而言,我在脚注处添加了脚本,并且可以正常工作

function api_test() {
   wp_localize_script( 'wp-api', 'wpApiSettings', array(
      'root' => esc_url_raw( rest_url() ),
      'nonce' => wp_create_nonce( 'wp_rest' )
   ) );
   wp_enqueue_script('app.script', '<script>/*call ajax here*/</script>');
}


add_action('wp_footer', 'api_test', 5);

add_action('in_admin_footer', 'api_test');