#44003 closed defect (bug) (invalid)
multiple wp_localize_script not working
Reported by: | gekomees | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | |
Component: | Script Loader | Keywords: | |
Focuses: | Cc: |
Description
Only the latest wp_localize_script is supplied to the javascript files regardless of handle in wp_localize_script function
I have two javascript enqueues and both have a wp_localize_script attached to them. However, only the latter wp_localize_script is actually applied to both of them.
This is my code:
<?php wp_register_script('filters', get_template_directory_uri() . '/theme/js/filters.js', false, '1.0.0', true); $localization = array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'language' => ICL_LANGUAGE_CODE ); wp_localize_script( 'filters', 'phpvariables', $localization ); wp_enqueue_script('filters'); $themejspath_url = get_template_directory_uri() . '/theme/js/functions.js'; $themejspath = get_template_directory() . '/theme/js/functions.js'; wp_register_script('ama', $themejspath_url, false, filemtime( $themejspath ), true); $localization = array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'purchaser_name' => __('Maksja nimi', 'ama'), 'purchaser_email' => __('Maksja e-mail', 'ama'), 'booker_name' => __('Broneerija nimi', 'ama'), 'booker_email' => __('Broneerija e-mail', 'ama'), ); wp_localize_script( 'ama', 'phpvariables', $localization ); wp_enqueue_script('ama');
It doesn't matter if wp_localize_script is on top or wp_enqueue_script.
The filters.js should get the localized array with the language variable but it doesn't. It gets the second one with the translatable strings.
This is the same even without WPML.
Commenting out the wp_localize_script( 'ama', 'phpvariables', $localization ); line allows the filters.js to get the localization with the language variable. This is strange, as the handles are different and thus the handler filters should not get the localization for the handler ama
Hello @gekomees, thanks for your report.
The second argument is the "object name" which needs to be unique as it's used as a global window variable in the form of
var phpvariables = { … }
. A secondvar phpvariables = { … }
will override the first one.To solve this you can add the handle as a prefix to the object name:
filtersPhpvariables
andamaPhpvariables
.