wp_localize_script( string $handle, string $object_name, array $l10n )
Localize a script.
Description
Works only if the script has already been added.
Accepts an associative array $l10n and creates a JavaScript object:
"$object_name" = {
key: value,
key: value,
...
}
See also
Parameters
- $handle
-
(string) (Required) Script handle the data will be attached to.
- $object_name
-
(string) (Required) Name for the JavaScript object. Passed directly, so it should be qualified JS variable. Example: '/[a-zA-Z0-9_]+/'.
- $l10n
-
(array) (Required) The data itself. The data can be either a single or multi-dimensional array.
Return
(bool) True if the script was successfully localized, false otherwise.
Source
File: wp-includes/functions.wp-scripts.php
function wp_localize_script( $handle, $object_name, $l10n ) { global $wp_scripts; if ( ! ( $wp_scripts instanceof WP_Scripts ) ) { _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ ); return false; } return $wp_scripts->localize( $handle, $object_name, $l10n ); }
Changelog
Version | Description |
---|---|
2.2.0 | Introduced. |
Example
You can access the variables in JavaScript as follows:
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.to send ajax request from theme files we can use wp_localize_script to globally declare our javascript variables.
in our js file we can use any of the globally declared variable
frontend_ajax_object.ajaxurl, frontend_ajax_object.data_var_1, frontend_ajax_object.data_var_1.
Example
You can access the variables in JavaScript as follows:
Note, calling this function multiple times in the a single session with the same object name will overwrite previous values,
If you need to have multiple data sets associated with the same script (handle), then you need to rename your object,
`wp_localize_script()` is often used to pass generic data from PHP to JavaScript, because it was originally the only official way to do that.
wp_add_inline_script() was introduced in WP v4.5, and is now the best practice for that use case. `wp_localize_script()` should only be used when you actually want to localize strings.