This function 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 was 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 WordPress Version 4.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.
$object_name is the name of the variable which will contain the data. Note that this should be unique to both the script and to the plugin or theme. Thus, the value here should be properly prefixed with the slug or another unique value, to prevent conflicts. However, as this is a JavaScript object name, it cannot contain dashes. Use underscores or camelCasing.
$l10n is the data itself. The data can be either a single- or multi- (as of 3.3) dimensional array. Like json_encode(), the data will be a JavaScript object if the array is an associate array (a map), otherwise the array will be a JavaScript array.
Furthermore, the actual output of the JavaScript <script> a 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.
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.
// 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:
// alerts 'Some string to translate'
alert( object_name.some_string );
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.
// Call a function that needs an int.
FinalZoom = map.getBoundsZoomLevel( bounds ) - parseInt( object_name.a_value, 10 );
What means Works only if the script has already been added? (added = Registered, Registered&Enqueued, Printed?)
Relating creates a JavaScript object, Where? (where = server-side js, in an extra .js file, in a script tag, or modifying the script given?)
What means …Script handle the data will be attached to? (attached = modify the script, print a script tag after the given script, delete or remove the original object if present from the given script?)
Actually an script tag with inline content is printed, but it gets printed before the script it belongs to, instead of after in the sense of attached, and the script will override it, if it contains for readability (say) the english-version of the object. — I suggest a warning on the behaviour of the function wp_localize_script. —
I do have more feedback: the example for $object_name, ‘/[a-zA-Z0-9_]+/’, does not lead to a qualified Javascript name, not even to a valid Javascript identifier, as it allows to begin with a digit. (It is not example, but a (not right) rule). May I suggest to drop the regex, and put perhaps a plain example name qualified by plugin prefix. Also I notice that the first line of the description (with the word added) should be the second line or dropped at all, such that the first line reads what the function does, and the restriction added is repeated later-on in different more precise words under IMPORTANT. Thank you for reading so far.
wp_register_script()::
Registers a script with WordPress.
Does not load the script on the page.
Useful when you want to define a script for later use with specific conditions or dependencies.
Takes arguments like script handle (unique identifier), script path (URL or relative path to the file), and optional arguments like version number and dependencies on other scripts.
wp_enqueue_script()::
Enqueues a script that need to be loaded on the page.
Can also register the script if it hasn’t been registered before.
Useful for including scripts you need on a specific page or based on certain conditions (e.g., only on the front-end).
Takes arguments like script handle (same as used with wp_register_script) and optional arguments like version number, dependencies, and placement (in the header or footer).
Here’s a key difference:
wp_enqueue_script can handle both registering and loading a script in one call.
wp_register_script only registers the script for later use with wp_enqueue_script or another function that might need it.
wp_localize_script()::
Does not register or enqueue a script.
Used to localize a registered script, meaning it injects PHP variables into the script as JavaScript objects.
Useful for passing data from WordPress (PHP) to your JavaScript code.
Takes arguments like script handle (of an already registered script), a variable name to hold the data in JavaScript, and the actual PHP data (array or object) you want to pass.
In short,
Use wp_register_script to define scripts for later use.
Use wp_enqueue_script to load scripts on the page (can also register if needed).
Use wp_localize_script to pass data from PHP to your registered JavaScript code.
Note, localizing boolean values will be cast to strings unless nested within an array.
The following localizes boolean values as top level items in the $l10n parameter:
wp_localize_script(
'scriptHandle',
'property',
array(
'isTrue' => true, // Localizes as a string value of "1"
'isFalse' => false, // Localizes as an empty string value of ""
)
);
Whereas the following localizes boolean values inside of a nested array in the `$l10n` parameter:
wp_localize_script(
'scriptHandle',
'property',
array(
array(
'isTrue' => true, // Localizes as a boolean value of `true`
'isFalse' => false, // Localizes as a boolean value of `false`
)
)
);
Further, as mentioned by Ian Dunn, wp_localize_scriptshould only be used to localize strings, which explains the above behavior.
Is there an alternative mechanism built in for passing other data besides strings to enqueued scripts? If not, your emphasized `should` should in my opinion be de-emphasized. Even the WordPress Codex points at usage other than localization: https://developer.wordpress.org/plugins/javascript/enqueuing/#localize
`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.
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.
wp_localize_script()
should not be used to pass arbitrary data to JavaScript, see: https://developer.wordpress.org/reference/functions/wp_localize_script/#comment-3213.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.wp_localize_script()
should not be used to pass arbitrary data to JavaScript, see: https://developer.wordpress.org/reference/functions/wp_localize_script/#comment-3213.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,
global $wp_scripts; $data = $wp_scripts->get_data( 'enqueued-script', 'data' ); if ( empty( $data ) ) { wp_localize_script( 'enqueued-script', 'obj', $localized_data ); } else { if ( ! is_array( $data ) ) { $data = json_decode( str_replace( 'var obj = ', '', substr( $data, 0, -1 ) ), true ); } foreach ( $data as $key => $value ) { $localized_data[ $key ] = $value; } $wp_scripts->add_data( 'enqueued-script', 'data', '' ); wp_localize_script( 'enqueued-script', 'obj', $localized_data ); }
Feedback: It would suggest for clarification:
Clearing confusion between all three functions. wp_enqueue_script() , wp_register_script() , and wp_localize_script()
wp_register_script()::
Registers a script with WordPress.
Does not load the script on the page.
Useful when you want to define a script for later use with specific conditions or dependencies.
Takes arguments like script handle (unique identifier), script path (URL or relative path to the file), and optional arguments like version number and dependencies on other scripts.
wp_enqueue_script()::
Enqueues a script that need to be loaded on the page.
Can also register the script if it hasn’t been registered before.
Useful for including scripts you need on a specific page or based on certain conditions (e.g., only on the front-end).
Takes arguments like script handle (same as used with wp_register_script) and optional arguments like version number, dependencies, and placement (in the header or footer).
Here’s a key difference:
wp_enqueue_script can handle both registering and loading a script in one call.
wp_register_script only registers the script for later use with wp_enqueue_script or another function that might need it.
wp_localize_script()::
Does not register or enqueue a script.
Used to localize a registered script, meaning it injects PHP variables into the script as JavaScript objects.
Useful for passing data from WordPress (PHP) to your JavaScript code.
Takes arguments like script handle (of an already registered script), a variable name to hold the data in JavaScript, and the actual PHP data (array or object) you want to pass.
In short,
Use wp_register_script to define scripts for later use.
Use wp_enqueue_script to load scripts on the page (can also register if needed).
Use wp_localize_script to pass data from PHP to your registered JavaScript code.
Note, localizing boolean values will be cast to strings unless nested within an array.
The following localizes boolean values as top level items in the
$l10n
parameter:Whereas the following localizes boolean values inside of a nested array in the `$l10n` parameter:
Further, as mentioned by Ian Dunn,
wp_localize_script
should only be used to localize strings, which explains the above behavior.