wp_localize_script( string $handle, string $object_name, array $l10n )

Localize a script.


Description 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 See also


Top ↑

Parameters 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.


Top ↑

Return Return

(bool) True if the script was successfully localized, false otherwise.


Top ↑

More Information More Information

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 can be used to make any data available to your script that you can normally only get from the server side of WordPress.

$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.

 

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> 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.


Top ↑

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


Top ↑

Changelog Changelog

Changelog
Version Description
2.2.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Codex

    Example

    // 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 ); 
    
  2. Skip to note 2 content
    Contributed by Aamer Shahzad

    to send ajax request from theme files we can use wp_localize_script to globally declare our javascript variables.

    function theme_enqueue_scripts() {
    	/**
    	 * frontend ajax requests.
    	 */
    	wp_enqueue_script( 'frontend-ajax', JS_DIR_URI . 'frontend-ajax.js', array('jquery'), null, true );
    	wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',
    		array( 
    			'ajaxurl' => admin_url( 'admin-ajax.php' ),
    			'data_var_1' => 'value 1',
    			'data_var_2' => 'value 2',
    		)
    	);
    }
    add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );

    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.

    jQuery(document).ready(function($) {
    	$.ajax({
            url: frontend_ajax_object.ajaxurl,
            type: 'get',
            data: {
                'action':'states_city_filter'
            },
            success: function( response ) {
            	console.log(response);
            },
        });
    });
  3. Skip to note 3 content
    Contributed by Ian Dunn

    `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.

  4. Skip to note 4 content
    Contributed by Aurovrata Venet

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

You must log in before being able to contribute a note or feedback.