Seb*_*lan 9 php wordpress jquery wordpress-theming wordpress-plugin
我的主题中有以下代码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');
Run Code Online (Sandbox Code Playgroud)
RRi*_*esh 15
您没有包含任何javascript文件wp_enqueue_script
.
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');
Run Code Online (Sandbox Code Playgroud)
创建一个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>
Run Code Online (Sandbox Code Playgroud)
然后pw_script_vars.alert
,您可以键入控制台以获取"Hey! You have clicked the button!"
消息.