Wp_localize_script not working

I have the following code in my topic functions.php, but when I call console.log(pw_script_vars);, a variable undefined. What did I miss?

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');
+5
source share
2 answers

You have not included a javascript file with yours 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');

Create an empty file with a name test.jsin your themes directory and it will work.

If you look at the source code, you will see:

<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>

You can then type pw_script_vars.alertin the console to receive the message "Hey! You have clicked the button!".

+12
source

You can also try to localize jQuery without having to create additional empty JS files.

    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')
    )
);

It works like a charm to me. Hope this helps.

+1
source

All Articles