What is the best way to pass a boolean into wp_localize_script as from what I can see everything is interpretted as strings.
I have a backend user options form for a plugin, when the values are returned I am using them for a jQuery script, one of them is a boolean, the user selects true or false from a dropdown, using wp_localize_script outputs these as strings (not booleans) “true” or “false” which will fail that parameter in the script.
<?php
$options = get_option('ng_slicknavmenu');
// Add PHP plugin variables to the $params[] array to pass to jQuery
$data = array (
'ng_slicknav_menu' => $options['ng_slicknav_menu'],
'ng_slicknav_parent_links' => $options['ng_slicknav_parent_links'], // this is a boolean true/false
'ng_slicknav_speed' => $options['ng_slicknav_speed'] ,
);
// Pass PHP variables to jQuery script
wp_localize_script( 'slickinit', 'phpVars', $data );
This is how I am doing it at the moment in my js init file
if( phpVars.ng_slicknav_parent_links === "true" )
$links = true;
else
$links = false;
jQuery(document).ready(function($){
ng_slicknav_speedInt = parseInt(phpVars.ng_slicknav_speed, 10);
jQuery(document).ready(function($) {
$(phpVars.ng_slicknav_menu).slicknav({
allowParentLinks: $links,
duration:ng_slicknav_speedInt,
});
});
});
But is there a better way?
I have tried some solutions from Passing boolean values with wp_localize_script …
'ng_slicknav_parent_links' => ($options['ng_slicknav_parent_links']) ? true : false,
and
'ng_slicknav_parent_links' => (bool)$options['ng_slicknav_parent_links'],
But the answer does not work. The answers there for both result in a string of “1” for both values which is incorrect.