Make WordPress Core

Opened 16 months ago

Last modified 16 months ago

#57405 new enhancement

wp_localize_script() doesn't decode html entities in nested arrays

Reported by: rilwis's profile rilwis Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: I18N Keywords: has-patch
Focuses: javascript Cc:

Description

If we localize a script with an array like this:

$data = [
    'key1' => 'Value 1',
    'key2' => [
        'subkey1' => 'String contains ' single quote encoded',
        'subkey2' => 'String contains " double quote encoded',
    ],
];

// Encoded strings stay encoded.
wp_localize_script( 'myhandle', 'myname', $data );

Then the outputted values of $data on the front end is exactly the same, e.g. encoded strings stay encoded:

array(2) {
  ["key1"]=>
  string(7) "Value 1"
  ["key2"]=>
  array(2) {
    ["subkey1"]=>
    string(43) "String contains ' single quote encoded"
    ["subkey2"]=>
    string(43) "String contains " double quote encoded"
  }
}

However, wp_localize_script() decode strings correctly if the array is not nested. So this code works correctly;

$data = [
    'key1' => 'Value 1',
    'key2_1' => 'String contains ' single quote encoded',
    'key2_2' => 'String contains " double quote encoded',
];

// Encoded strings are decoded.
wp_localize_script( 'myhandle', 'myname', $data );

Output:

array(3) {
  ["key1"]=>
  string(7) "Value 1"
  ["key2_1"]=>
  string(38) "String contains ' single quote encoded"
  ["key2_2"]=>
  string(38) "String contains " double quote encoded"
}

This inconsistent behavior might cause issues when JS outputs/uses the text directly.

I'd suggest making the wp_localize_script function decoded strings in all cases.

Attachments (1)

57405.patch (870 bytes) - added by dilipbheda 16 months ago.
Here is the patch to fix this issue.

Download all attachments as: .zip

Change History (2)

@dilipbheda
16 months ago

Here is the patch to fix this issue.

#1 @dilipbheda
16 months ago

  • Keywords has-patch added

Hello @rilwis,

Thank you for the ticket, I've reviewed this issue and fixed it with the attached patch.

Thanks

Note: See TracTickets for help on using tickets.