wp_localize_script()WP 2.2.0

Localize a script. 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, ... }

Works only if the script has already been registered.

Accepts an associative array $l10n and creates a JavaScript object:

"$object_name" = {
	key: value,
	key: value,
	...
}

No Hooks.

Return

true|false. True if the script was successfully localized, false otherwise.

Usage

wp_localize_script( $handle, $object_name, $l10n );
$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.

Examples

1

#1 Do not use wp_localize_script() for data transfer

wp_localize_script() is recommended to use only for passing localization strings, not for passing data. For pass objects that your JS will use, It is better to use wp_add_inline_script().

Let's look at an example:

In the past you could (and still can) do the following:

wp_enqueue_script( 'my-script', 'https://url-to/my-script.js' );

wp_localize_script( 'my-script', 'MYSCRIPT', array(
	'ajaxUrl' => admin_url( 'admin-ajax.php' ),
	'otherParam' => 'some value',
) );

But it is better to do it this way, because in this case we preserve the types of data transmitted and, for example, numbers will remain numbers and not turn into strings:

wp_enqueue_script( 'my-script', 'https://url-to/my-script.js' );

$data = wp_json_encode( [
	'ajaxUrl' => admin_url( 'admin-ajax.php' ),
	'param_one' => 'some value',
	'param_two' => 25,
] );

wp_add_inline_script( 'my-script', "const myScriptData = $data", 'before' );

Note that you must add 'before' as a third parameter.

Now you can get this data in a JS script as follows:

console.log( myScriptData.ajaxUrl );   // "https://site.com/wp-admin/admin-ajax.php"
console.log( myScriptData.param_one ); // "some value"
console.log( myScriptData.param_two ); // 25
0

#2 Inserting global data

An example of inserting global javascript data before the JS script (in the example, the script is jquery). Use this code in functions.php:

add_action( 'wp_enqueue_scripts', 'action_function_name_7714', 99 );

function action_function_name_7714(){

	wp_localize_script( 'jquery', 'object_name', array(
		'some_string' => __( 'Some string to translate' ),
		'some_num' => '10'
	) );
}

We'll get it in the head part of the site:

<script type='text/javascript'>
/* <![CDATA[ */
var object_name = {"some_string":"Some string to translate","some_num":"10"};
/* ]]> */
</script>
<script type='text/javascript' src='http://example.com/wp-includes/js/jquery/jquery.js?ver=1.8.3'></script>
0

#3 Define the AJAX request handler file

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.

Let's add the script and then the global data to it. Here we add a javascript file with an AJAX request. The file uses the variable MyAjax.ajaxurl as the URL to direct the AJAX request. We will define this URL through wp_localize_script():

add_action( 'wp_enqueue_scripts', 'action_function_name_7714' );

function action_function_name_7714(){

	wp_enqueue_script( 'my-ajax', get_template_directory_uri() . '/js/custom_script.js' );

	wp_localize_script( 'my-ajax', 'MyAjax', [ 'ajaxurl' => admin_url( 'admin-ajax.php' ) ] );

}

we get:

<script type='text/javascript'>
/* <![CDATA[ */
var MyAjax = {"ajaxurl":"http://example.com/wp-admin/admin-ajax.php"};
/* ]]> */
</script>
<script type='text/javascript' src='http://example.com/wp-content/themes/twentyeleven/js/custom_script.js?ver=3.5'></script>

Access to variables in Javascript is as follows (for Example 2):

<script>
// in the file custom_script.js we can use a variable: MyAjax.ajaxurl
alert( MyAjax.ajaxurl ); // print http://example.com/wp-admin/admin-ajax.php
</script>
0

#4 Calling this function multiple times

Note, calling this function multiple times in the a single session with the same object name will overwrite previous values:

wp_localize_script( 'some_handle', 'object_name', $value1 );
... code executed again...
wp_localize_script( 'some_handle', 'object_name', $value2 ); 
// object_name is now set to $value2.

If you need to have multiple data sets associated with the same script (handle), then you need to rename your object,

wp_localize_script( 'some_handle', 'object_name1', $value1 );
... code executed again...
wp_localize_script( 'some_handle', 'object_name2', $value2 );
Variant

Or remove the original code and replace with the code you need:

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 );
}

Notes

Changelog

Since 2.2.0 Introduced.

Code of wp_localize_script() WP 5.9.3

function wp_localize_script( $handle, $object_name, $l10n ) {
	global $wp_scripts;

	if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
		_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
		return false;
	}

	return $wp_scripts->localize( $handle, $object_name, $l10n );
}