wp_localize_script unexpectedly converts numbers to strings
|Reported by:||adamsilverstein||Owned by:|
|Component:||I18N||Keywords:||has-patch dev-feedback 4.1-early|
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 (35)
comment:1 @c3mdigital — 19 months ago
- Keywords close added; dev-feedback removed
comment:2 follow-up: ↓ 3 @c3mdigital — 19 months ago
comment:5 @c3mdigital — 19 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
- Keywords dev-feedback added
comment:18 follow-up: ↓ 19 @helen — 9 months ago
- Keywords 4.1-early added
- Milestone changed from 4.0 to Future Release