Localizes a registered script with data for a JavaScript variable.
This lets you offer properly localized translations of any strings used in your script. This is necessary because WordPress currently only offers a localization API in PHP, not directly in JavaScript (but see ticket #20491).
Though localization is the primary use, it can be used to make any data available to your script that you can normally only get from the server side of WordPress.
<?php wp_localize_script( $handle, $name, $data ); ?>
<?php // Register the script wp_register_script( 'some_handle', 'path/to/myscript.js' ); // Localize the script with new data $translation_array = array( 'some_string' => __( 'Some string to translate', 'plugin-domain' ), 'a_value' => '10' ); wp_localize_script( 'some_handle', 'object_name', $translation_array ); // Enqueued script with localized data. wp_enqueue_script( 'some_handle' );
You can access the variables in JavaScript as follows:
<script> // alerts 'Some string to translate' alert( object_name.some_string); </script>
Note: The data in the resulting JavaScript call will be passed as text (see ticket #25280). If you are trying to pass integers you will need to call the JavaScript parseInt() function.
<script> // Call a function that needs an int. FinalZoom = map.getBoundsZoomLevel( bounds ) - parseInt( object_name.a_value, 10 ); </script>
Another example in case you need the plugins URL, which might be handy:
wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js'); wp_localize_script('my-script', 'myScript', array( 'pluginsUrl' => plugins_url(), ));
Now you will have access to myScript.pluginsUrl in your script file:
var href = myScript.pluginsUrl + '/path/to/resource';
IMPORTANT! wp_localize_script() MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script().
Furthermore, the actual output of the JavaScript <script>
tag containing your localization variable occurs at the time that the enqueued script is printed (output/included on the page). This has some significant repercussions if you enqueue your script as you should using the appropriate actions (wp_enqueue_scripts and admin_enqueue_scripts), but wish to localize later using data that is not available at enqueue time.
In this case, consider enqueueing your script with the in_footer argument set to true, to delay the printing of your script include until much later in the page build (ie: wp_enqueue_script( $slug, $URL, $deps, $ver, true );
). The last chance to localize your script would then be on the 'wp_print_footer_scripts' hook.
wp_localize_script() is located in wp-includes/functions.wp-scripts.php
.
Enqueue Styles
Enqueue Scripts
Front-End Hooks
Admin Hooks
Login Hooks