因此,我在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>我想运行这个例子,但是控制台说
未定义的ReferenceError: wpApiSettings未定义
我做错了什么?谢谢!
发布于 2016-06-24 06:10:27
请看下面的示例:script
您需要wp_register_script和wp_enqueue_script,否则将不会创建JS变量。
发布于 2022-03-08 19:58:39
将以下代码添加到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');https://stackoverflow.com/questions/37847901
复制相似问题