wp_localize_script not working
Asked Answered
S

5

12

I have the following code in my theme functions.php but when I call console.log(pw_script_vars); the variable is 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');
Sommelier answered 15/4, 2013 at 8:32 Comment(0)
B
23

You didn't include any javascript file with your 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 called test.js in your theme directory and it will work.

If you then look at your source code you'll 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.alert in your console to get the "Hey! You have clicked the button!" message.

Bahaism answered 15/4, 2013 at 9:41 Comment(4)
Thank you for your response, but my intention was to pass some php arrays in jquery where I can appeal on every page of my template ...Ja
That's exactly what the code above did. Did you have any issues?Bahaism
I got the script from: papermashup.com/jquery-iphone-style-ajax-switch and I made: wp_enqueue_script('ajax-switch', get_bloginfo('template_url').'/includes/ajaxswitch/jquery.iphone-switch.js', false, false); global $current_user; wp_localize_script('ajax-switch', 'ajax_switch', array( 'post_status' => get_user_meta($current_user->ID, '_fbpost_status', true), 'templateUrl' => get_template_directory_uri().'/includes/ajaxswitch/' ) ); And worken thank you so much, the second thing is that in those php files I need to include the wordpress variables and php library. How?Ja
The response was #specify host or domain (needed for wp-includes/ms-settings.php:100) $_SERVER[ 'HTTP_HOST' ] = 'localhost'; #location of wp-load.php so we have access to database and $wpdb object $wp_load_loc = "../../../../../wp-load.php"; require_once($wp_load_loc); Ja
C
4

You could also try to localize jQuery without the need 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 for me. Hope it helps.

Complaisant answered 7/5, 2015 at 8:28 Comment(0)
B
1
Place the code block below the wp_enqueue_script    



     $dir_url = array( 'dir_url' => get_stylesheet_directory_uri() );
        wp_localize_script( 'custom-js', 'adact_img', $dir_url );



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' />"],
            });


        
Boxhaul answered 5/4, 2021 at 3:39 Comment(0)
B
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' />"],
            });


        
Boxhaul answered 5/4, 2021 at 3:38 Comment(0)
B
0

It helped me when I called translations after initializing the translation files

function ap_action_init(){
// Локализация
    load_plugin_textdomain('cf7lg', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
    wp_enqueue_script('pw-script', get_template_directory_uri() . '/translate.js', 1000);
    wp_localize_script('pw-script', 'cf7lgTranslate', array(
            'success' => __('Data saved successfully', 'cf7lg'),
            'error' => __('Failed to send data', 'cf7lg'),
            'failed' => __('Request failed', 'cf7lg'),
            'error_input_amount' => __('Please use numbers or the [amount-product] template.', 'cf7lg'),
    )); 
}
add_action('init', 'ap_action_init');

And now I have the translations for the js strings working.

Beauteous answered 3/5 at 7:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.