0

I am a little confused on this function.

I have it working for one javascript variable. I tried to get it working for two others and it found that it repeats the code in the header 3 times. I tried using an array for the handle but that just broke the code

 <?php wp_localize_script( $handle, $name, $data ); ?> 




 function localize_my_script() {
$image_url = get_template_directory_uri() . '/images/supersized/';
$src = get_template_directory_uri() . '/images/preload.gif';
$swfLocation = get_template_directory_uri() . '/js/audiojs.swf';

$localizations = array( 'image_path' => $image_url, 'src' => $src, 'swfLocation' => $swfLocation );

wp_localize_script( 'shutter', 'scriptvars', $localizations );
//wp_localize_script( 'preloader', 'script', $localizations );
//wp_localize_script( 'audio', 'scriptv', $localizations );
 }
 add_action( 'wp_enqueue_scripts', 'localize_my_script' );

with the two lines commented out above, the script only prints one line of code in the header for all three variables. But if I uncomment the 2, then it prints them three times. It includes all three variables in that one line of code. So how to I get the handles in there so it doesn't make 2 more lines of code?

0

That's how the wp_localize_script function works. It prints all the variables before your script is included to make sure that the variables are available to the script. If you want to print the localized variables only one time, but make sure that they are accessible for all three scripts - you can do that by setting dependencies when enqueueing/registering your scripts. So, register the 'audio' and 'preloader' scripts with dependency set to 'shutter' (WordPress will then make sure that 'shutter' is included before 'preloader' and 'audio'), and then localize only the 'shutter' script.

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.