1

I don't get how script localization works in wordpress. I created an associative array in php:

$translations = array(
    'value1'  =>'This is first value',
    'value2'  =>'This is second value'
    ); 

I created simple javascript file where I want to use this array:

jQuery(document).ready(function($){
    alert(translations);
});

Then I try to enqueue and localize this javascript file in my plugin like this:

function kvkoolitus_load_comment_validation(){
  wp_enqueue_script( 'simple-js', plugin_dir_url( __FILE__ ) . 'js/jquery.simple.js', array('jquery'), '', true );
  wp_localize_script( 'simple-js', 'translations', $translations );
}

add_action( 'wp_enqueue_scripts', 'kvkoolitus_load_comment_validation' );

But when I load a page with this javascript file, alert tells me that 'translations' object is null.
What did I miss?

2
  • Where did you place $translations = array( 'value1' =>'This is first value', 'value2' =>'This is second value' ); ? It should be added in the kvkoolitus_load_comment_validation function Commented Jul 13, 2016 at 19:16
  • Don't understand why array should by inside this function, but it works. Thanks czerspalace! Add this as an answer and I will accept it! Commented Jul 13, 2016 at 19:57

1 Answer 1

1

Copying from the answer here regarding variable scope

Variables inside a function are only available inside that function. 
Variables outside of functions are available anywhere outside of functions, 
but not inside any function.

Because of that, you need to add your $translations array within the kvkoolitus_load_comment_validation function, like

function kvkoolitus_load_comment_validation(){
  $translations = array(
    'value1'  =>'This is first value',
    'value2'  =>'This is second value'
  ); 
  wp_enqueue_script( 'simple-js', plugin_dir_url( __FILE__ ) . 'js/jquery.simple.js', array('jquery'), '', true );
  wp_localize_script( 'simple-js', 'translations', $translations );
}

add_action( 'wp_enqueue_scripts', 'kvkoolitus_load_comment_validation' );
1
  • I forgot about scope, damn, I need a vacation. Thanks czerspalace! Commented Jul 14, 2016 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.