php - wp_localize_script 不工作

标签 php jquery wordpress wordpress-theming

我的主题 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/

相关文章:

php - PHP 查询中的等于和不等于

php - 从 Laravel 框架创建一个在线用户(问题)

asp.net - 最佳实践 - 从代码隐藏中设置 jQuery 属性

javascript - (jQuery) .hover() 中淡入/淡出元素的问题

php - 错误 : When i try to install php 7 version on centos 7 but Package comes Php 5 version

php - 如何从购物车和结帐页面 woocommerce 中删除订单总额

PHP和 Controller : Browser don't find Base Controller

php - 使用 PHP 以编程方式显示违反 MySQL 唯一约束的列名

php - 多个查询 MySQL 与 PHP

javascript - JQuery - 只需走进主要的 li 元素