wp_localize_script无效

时间:2013-04-15 08:32:32

标签: php jquery wordpress wordpress-plugin 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');

4 个答案:

答案 0 :(得分:15)

您没有在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以获取"Hey! You have clicked the button!"消息。

答案 1 :(得分:3)

您也可以尝试本地化jQuery,而无需创建额外的空JS文件。

    wp_localize_script('jquery', 'pw_script_vars', array(
        'alert' => __('Hey! You have clicked the button!', 'pippin'),
        'message' => __('You have clicked the other button. Good job!', 'pippin')
    )
);

它对我来说就像一个魅力。希望它有所帮助。

答案 2 :(得分:0)

Place the code block below the wp_enqueue_script    

Then Add it as a variable on your custom script. Here is called "custom-js"

    var dir_url = adact_img.dir_url;
       $('hello') .owlCarousel({
                items: 1,
                loop: true,
                margin: 0,
                dots: false,
                nav: true,
                navText: ["<img src='"+ dir_url +" /assets/images/icons/angle-right.png' />", "<img src='"+ dir_url +" /assets/images/icons/angle-left.png' />"],
            });


        

答案 3 :(得分:0)

CountIF