我的主题 functions.php
中有以下代码,但是当我调用 console.log(pw_script_vars);
时,变量是 undefined
.我错过了什么?
function mytheme_enqueue_scripts(){
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts');
function pw_load_scripts() {
wp_enqueue_script('pw-script');
wp_localize_script('pw-script', 'pw_script_vars', array(
'alert' => __('Hey! You have clicked the button!', 'pippin'),
'message' => __('You have clicked the other button. Good job!', 'pippin')
)
);
}
add_action('wp_enqueue_scripts', 'pw_load_scripts');
最佳答案
您没有在您的 wp_enqueue_script
中包含任何 javascript 文件。
function pw_load_scripts() {
wp_enqueue_script('pw-script', get_template_directory_uri() . '/test.js');
wp_localize_script('pw-script', 'pw_script_vars', array(
'alert' => __('Hey! You have clicked the button!', 'pippin'),
'message' => __('You have clicked the other button. Good job!', 'pippin')
)
);
}
add_action('wp_enqueue_scripts', 'pw_load_scripts');
在您的主题目录中创建一个名为 test.js
的空文件,然后
它会起作用。
如果您随后查看源代码,您会看到:
<script type='text/javascript'>
/* <![CDATA[ */
var pw_script_vars = {"alert":"Hey! You have clicked the button!","message":"You have clicked the other button. Good job!"};
/* ]]> */
</script>
然后您可以在控制台中键入 pw_script_vars.alert
以获取“嘿!您已单击按钮!”
消息。
关于php - wp_localize_script 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010820/