Make WordPress Core

Opened 2 years ago

Last modified 13 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 2nd-opinion close
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 2 years ago.
Here is the patch to fix this issue.

Download all attachments as: .zip

Change History (3)

@dilipbheda
2 years ago

Here is the patch to fix this issue.

#1 @dilipbheda
2 years 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

#2 @swissspidy
13 months ago

  • Keywords 2nd-opinion close added

I don't think we'd want to modify wp_localize_script like this. The functionality has been largely unchanged for many years and there are multiple known oddities like this.

Nowadays there are better alternatives such as wp_add_inline_script and wp_set_script_translations.

Note: See TracTickets for help on using tickets.