Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Currently using this simplified code to pass data from WP to JS.

function add_map_data() {

        $objName = "MapData";
        $array = array(
            "MapViewLatitude" => "51.505",
            "MapViewLongitude" => "-0.09",

        );

        wp_enqueue_script( 'mapdata', get_bloginfo('template_url').'/custom/map.js', null, null, false );
        wp_localize_script( 'mapdata', $objName, $array );
}
add_action( 'wp_enqueue_scripts', 'add_map_data');

The only issue is that this is passing object.
How can I pass data in JSON format?

Any suggestion much appreciated.

share|improve this question

1 Answer 1

Try wrapping your array in json_encode():

function add_map_data() {

        $objName = "MapData";
        $array = array(
            "MapViewLatitude" => "51.505",
            "MapViewLongitude" => "-0.09",

        );

        wp_enqueue_script( 'mapdata', get_bloginfo('template_url').'/custom/map.js', null, null, false );
        wp_localize_script( 'mapdata', $objName, array('my_arr' =>json_encode($array)));
}
add_action( 'wp_enqueue_scripts', 'add_map_data');

Next step is to parse the JSON string back to a JSON object in JavaScript so:

//first escape the string then parse this string and convert it into a JSON object
var MapDataJSON = jQuery.parseJSON(MapData.my_arr.replace(/"/g, '"'));
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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