wp_localize_script(): What can you do with that third arg?

Let’s start with this, the param descriptions for wp_localize_script():

 * @param string $handle      Script handle the data will be attached to.
 * @param string $object_name Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
 *                            Example: '/[a-zA-Z0-9_]+/'.
 * @param array $l10n         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.
function wp_localize_script( $handle, $object_name, $l10n ) {


So you’re passing an array, right? Good.

If you’re not, tsk tsk. But let’s take a look at the good and the bad…

Array. Expected usage, you’re okay here:

wp_localize_script( 'jquery', 'exampleObject1', [
    'key' => 'value',
] );
// var exampleObject1 = {"key":"value"};

wp_localize_script( 'jquery', 'exampleObject2', [
] );
// var exampleObject2 = ["value"];

String. Hit and miss:

wp_localize_script( 'jquery', 'exampleObject3', 'string' );
// var exampleObject3 = "string";

Above works by coincidence. This shouldn’t be relied upon.

wp_localize_script( 'jquery', 'exampleObject4', '' );
// var exampleObject4 = "";

Above throws a warning:

PHP Warning: Cannot assign an empty string to a string offset

Reduced example of the difference:

$l10n = 'string';
$l10n[0] = $l10n; // okay

$l10n = '';
$l10n[0] = $l10n; // warning. There's no character at the zeroth place to replace

Scalar. Miss (maybe hit because PHP is wacko):

wp_localize_script( 'jquery', 'exampleObject5', true );
// var exampleObject5 = true;

Above throws warning:

Cannot use a scalar value as an array

wp_localize_script( 'jquery', 'exampleObject6', false ); // no error
// var exampleObject6 = [""];

However, the above does not.

Reduced example, though it won’t really clarify things:

$true = true;
$false = false;

var_dump( is_scalar( $true ) ); // true
var_dump( is_scalar( $false ) ); // true

$true[] = 'adsf'; // Cannot use a scalar value as an array 
$false[] = 'jkl'; // okay why not

var_dump( $true ); // true
var_dump( $false ); // [ 0 => 'jkl' ] 

Why? No really, I’m asking.

So listen to the docs, and use an array.

Leave a Reply

Your email address will not be published. Required fields are marked *