wp_localize_script unexpectedly converts numbers to strings
|Reported by:||adamsilverstein||Owned by:|
|Component:||I18N||Keywords:||has-patch dev-feedback needs-testing|
Running wp_localize_script on an an array has the unexpected result of converting numbers into strings. Core WordPress files work around this issue by explicitly casting variables to int, for example in revisions.js.
The root of the problem is that in PHP versions before 5.3.3, json_encode encoded numbers as strings. PHP 5.3.3 includes an option JSON_NUMERIC_CHECK that eliminates this issue.
For example & testing this bug, add the following code to your template's setup function:
wp_enqueue_script( 'localize_test', get_template_directory_uri() . '/localize_script.js', array(), '1.0.0', true ); $array_to_localize = array( 'a_string' => __( 'Some String' ), 'a_number' => 10, ); wp_localize_script( 'localize_test', 'localized_variable', $array_to_localize );
Then add a file named localize_script.js in your theme folder containing the following code:
Reloading shows that the number has been converted into a String (console screenshot).
The attached patch corrects the issue by checking for the presence of the JSON_NUMERIC_CHECK constant and if present, passes it to json_encode - telling it to encode numbers as numbers and resulting in the expected behavior (console screenshot). I checked this under PHP 5.2.17 verifying that no errors are created (although the old behavior of converting numbers still occurs). Under PHP 5.3.3 the variable is now properly passed as a number. The Codex documentation needs to be updated if this patch is accepted.
Change History (14)
comment:1 c3mdigital — 7 months ago
- Keywords close added; dev-feedback removed
comment:2 follow-up: ↓ 3 c3mdigital — 7 months ago
comment:5 c3mdigital — 7 months ago
- Keywords dev-feedback added; close removed
- Type changed from defect (bug) to enhancement
- Version changed from trunk to 3.2
- Summary changed from wp_localize_script unexpectedly convert numbers to strings to wp_localize_script unexpectedly converts numbers to strings