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?

  • 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 – czerspalace Jul 13 '16 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! – anton Jul 13 '16 at 19:57
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' );
  • I forgot about scope, damn, I need a vacation. Thanks czerspalace! – anton Jul 14 '16 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.