wp_localize_script unexpectedly converts numbers to strings
|Reported by:||adamsilverstein||Owned by:|
|Component:||Script Loader||Keywords:||has-patch dev-feedback|
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 (41)
4 years ago
- Keywords close added; dev-feedback removed
4 years 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
- Keywords 4.1-early added
- Milestone changed from 4.0 to Future Release