wp_localize_script()WP 2.2.0

Adds additional data before the specified script that is queued for output.

The function is created to add localization data to a JS script. This function registers data for the specified script, then before the output (enqueuing) of the script itself, the data specified in this function is output in a <script> tag as a JS object.

This function needs to be called:

  • after the script has been registered. See wp_register_script().
  • or after the script has been added to the queue for output. See wp_enqueue_script().
  • or if the script already exists in WordPress.

If the script has already been output to the screen and this function is used afterward, nothing will happen.

In other words, the script to which this function is connected must be:

At the same time, at the moment of using this function, the script to which this function is connected must not have been output yet. In code, it should look like this:

// register the script
wp_register_script( $id, ... )

// add data to the registered script
wp_localize_script( $id, ... )

// enqueue the script for output
wp_enqueue_script( $id )

Or if so, when the script is immediately enqueued for output (without prior registration):

// register and enqueue the script for output
wp_enqueue_script( $id, ... )

// add data to the registered script
wp_localize_script( $id, ... )

This function needs to be called through hooks because at the time these hooks are triggered, all scripts are usually registered but not yet output in HTML:

For localization only!

This function is often used to add data to the script, rather than for connecting localization strings. For example, when connecting a slider, its settings are connected before it.

This is not recommended! Use this function only for localization, and for adding additional data use wp_add_inline_script(). See example.

Data in the final Javascript will be passed as text.
If you need to process numbers, you should use the parseInt() function in the receiving script:

<script>
FinalZoom = map.getBoundsZoomLevel( bounds ) - parseInt( data.a_value );
</script>

EXCEPTION. If jquery is specified in $handle, then localization will be connected to the jquery-core script.

But if you have overridden the jQuery connection (specified that it should be loaded from an external resource, i.e., removed the basic connection option in WordPress and specified your own), then the jquery-core script will be disabled, which means that localization will not work because it connects to jquery-core, which no longer exists.

To unequivocally avoid both of these inconsistencies, you need to do this::

add_action( 'wp_enqueue_scripts', 'front_scripts' );

function front_scripts(){

	$jquery_url = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';

	wp_deregister_script( 'jquery-core' );
	wp_deregister_script( 'jquery' );

	wp_register_script( 'jquery-core', $jquery_url, false, null, true );
	wp_register_script( 'jquery', false, [ 'jquery-core' ], null, true );
}

No Hooks.

Returns

true|false.

Usage

wp_localize_script( $handle, $object_name, $l10n );
$handle(string) (required)
The name of the script before which the data will be added. The script must be registered in advance.
$object_name(string) (required)
The name of the Javascript object that will contain the data. The name must be unique to avoid conflicts with other scripts! The name cannot use a hyphen -, only Latin letters a-zA-Z, underscores _, and you can also apply the "camelCase" method.
$l10n(array) (required)
Translation data. The data can be either a one-dimensional or a multi-dimensional array.

Examples

2

#1 Do not use wp_localize_script() for data transfer

wp_localize_script() is recommended to be used only for passing localization strings, not for passing data - an object that your script will use. For passing data, it's better to use wp_add_inline_script().

Let's consider an example:

Previously, you could (and still can) do the following:

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

wp_localize_script( 'my-script', 'myScriptData', [
	'ajax_url'  => admin_url( 'admin-ajax.php' ),
	'param_one' => 'some value',
	'param_two' => 25,
] );

But it's better to do it differently to preserve the types of the transmitted data - numbers will remain numbers, booleans true/false, and will not turn into strings:

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

$js = 'window.myScriptData = ' . wp_json_encode( [
	'ajax_url'  => admin_url( 'admin-ajax.php' ),
	'param_one' => 'some value',
	'param_two' => 25,
] );

wp_add_inline_script( 'my-script', $js, 'before' );

Note that you need to add 'before' as the third parameter.

Now in the JS script, you can access this data like this:

console.log( myScriptData.ajax_url );  // "https://example.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.

wp_localize_script() code WP 6.9.1

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

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