Using wp_localize_script with jQuery variables including strings, booleans and integers
By default the values are retrieved as strings even the boolean and integer values.
How wp_localize_script works
<?php wp_localize_script( $handle, $name, $data ); ?>
In the above is a plugin example that is using wp_localize_script so the $handle it is using is the ‘jsinit‘ script this is the script that we wish to transfer our PHP variables to.
The $name is set to ‘phpVars‘ which will be used to prefix the PHP variables.
The $data is set in an array and is pulling out 4 values from our ‘wpb_stored_options_test‘ which already have been defined.
Most importantly the wp_localize_script is executed before the jsinit script is enqueued, otherwise the variables can’t be supplied to it.
Referencing the values in the jQuery init file
So this is how in the ‘jsinit‘ file the PHP variables are pulled in, note how the $name phpVars is used as a prefix.
You will see these values in the source code like so
So these are the PHP variables being passed to our ‘initjs’ script via the wp_localize_script API, they are wrapped in a script tag and CDATA tags. This all works as intended with strings but notice that our integer and boolean values are also interpreted as strings, you may want to pass these values into your script as true booleans and integers.
You can achieve this by wrapping your $data values inside an inner array and declaring the value as a boolean or integer by the process of type casting.
So in the above note the inner array on the $data called wpb_stored_inner and also our boolean and integer values are cast with (bool) and (int). The last thing to do is reference the values in the ‘initjs’ file which now has to include the inner array in the path of the value.
The values now have a prefix of phpVars.wpb_stored_inner and then the value.
This will then result in preserved boolean and integers values being passed.
So now in the above the wpb_stored_number has a integer value and wpb_stored_truth has a boolean.
Leave all Comment