I am using wp_localize_script to pass a couple of values from my theme options to a javascript file. First I got the values from my theme options:

$options = get_option('theme');  
$flex_auto = $options["slide-auto"];
$flex_animation = $options["slide-animation"];
$flex_direction = $options["slide-direction"];

Then I used wp_localize_script to create my array of values.

wp_localize_script('flexslider', 'flex_vars', array(
    'flex_auto' => $flex_auto,
    'flex_animation' => $flex_animation,
        'flex_direction' => $flex_direction

In my javascript file I did this:

var $anim = flex_vars.flex_animation;
var $auto = flex_vars.flex_auto;
var $dire = flex_vars.flex_direction;

    animation: $anim,
    slideshow: $auto,
    controlNav: 'thumbnails',
    directionNav: $dire, 
    slideshowSpeed: 7000,
    animationSpeed: 1000,
    touch: true,

My theme options include some values that are made with checkboxes which work with 0/1 booleans while the jQuery plugin I'm using works with true/false. I tried saving the boolean value as strings by using a drop-down menu with two options, either true or false, but that doesn't seem to work. How can I pass the boolean values from the theme options to the javascript file? Any suggestions and hints very welcome :)


Try this:

$options = get_option( 'theme' );

wp_localize_script( 'flexslider', 'flex_vars', array (
  'flex_auto' => ($options['slide-auto']) ? 'true' : 'false',
  'flex_animation' => $options['slide-animation'],
  'flex_direction' => $options['slide-direction']
) );

Assuming slide-auto is the option you made a boolean.

This script isn't tested, I directly typed it in here.

| improve this answer | |
  • Ok tried it and I had to remove the little apostrophies around true and false. So it looks more like this now: 'flex_auto' => ($options['slide-auto']) ? true : false, Thanks so much! – charlenemasters Jul 5 '13 at 10:42
  • 4
    For just forcing type to boolean better way to write it would be with (bool) $options['slide-auto'] cast. – Rarst Jul 5 '13 at 11:50
  • 1
    Worth noting that in my wp 3.8.1 I get not strictly true or false, but "1" or "": var PARAMS = {"true":"1","false":""}; – Dmitry Mukhin Feb 5 '14 at 2:34
  • To avoid the stringification of the cast values you can use a nested array - see wordpress.stackexchange.com/a/186191/57034. – bonger May 7 '15 at 1:19

This is the right answer working for me

wp_add_inline_script('helloworld','var site_config ='.json_encode(array (<Your array>)));

wp_localize_script with boolean and init

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.