Opened 4 years ago
Last modified 2 years ago
#57405 new enhancement
wp_localize_script() doesn't decode html entities in nested arrays
| Reported by: | rilwis | Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | Awaiting Review |
| Component: | I18N | Version: | |
| Severity: | normal | Keywords: | has-patch 2nd-opinion close |
| Cc: | Focuses: | javascript |
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)
Change History (3)
#1
@
4 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
@
2 years 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.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
Here is the patch to fix this issue.