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

Localizes a script.

Description

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

See also

Parameters

$handlestringrequired
Script handle the data will be attached to.
$object_namestringrequired
Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
Example: '/[a-zA-Z0-9_]+/'.
$l10narrayrequired
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.

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

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.

Source

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

Changelog

VersionDescription
2.2.0Introduced.

User Contributed Notes

  1. Skip to note 7 content

    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);
            },
        });
    });
  2. Skip to note 8 content

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

  3. Skip to note 9 content

    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 ); 
  4. Skip to note 10 content

    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 );
  5. Skip to note 11 content

    Feedback: It would suggest for clarification:

    • 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?)
  6. Skip to note 12 content

    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_script should only be used to localize strings, which explains the above behavior.

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