WP-API 2 Cookie身份验证



所以,我在wordpress(wp-api 2)中有一个php页:

<?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>

我想运行此示例,但控制台说

未介绍的参考文献:未定义wpapisettings

我在做什么错?谢谢!

在此处查看示例:https://codex.wordpress.org/function_reference/wp_localize_script

您需要wp_register_script和wp_enqueue_script或JS变量不会创建。

将以下代码添加到functions.php,并检查用户是否已经登录的用户是否具有发布功能(创建产品,发布,上传媒体文件等)

/*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');

最新更新