I’ve got a working piece of javascript that contains an object literal.
But I need to localize it, and I’m ytrying to figure out how to rewrite it so that I can get wp_localize_script() to accet it, and output the correct format.
The non-localized (non dynamic) version looks like this:
var layoyt_config = {
'header' : 1
, 'footer' : 1
, 'ls' : {'sb1':1}
, 'rs' : {'sb1':1,'sb2':1}
, 'align' : 'center'
};
Now, to have those values generated by php (based on some wp_settings) I want to use wp_localize_script, so I can take it from there:
var layoyt_config = my_localized_data.layoyt_config;
And to get that data in to that object property I ‘thought’ I could do this, but obviously not:
$data = array(
'layout_config' => {
'header' : 1
, 'footer' : 1
, 'ls' : {'sb1': 1}
, 'rs' : {'sb1': 1,'sb2': 1}
, 'align' : 'center'
}
);
wp_localize_script('my-script-handle', 'my_localized_data', $data);
As this will cause PHP parse error I’ve tried to rewrite the json to array syntax, as wp_localize_script will convert that back to object notation, but this also does not work for me:
$data = array(
'layout_config' => array(
'header' => 1
, 'footer' => 1
, 'ls' => array('sb1'=>1)
, 'rs' => array('sb1'=>1,'sb2'=>1)
, 'align' => 'center'
)
);
wp_localize_script('my-script-handle', 'my_localized_data', $data);
And while this runs smoothly trhough the php parser, I do not get the expected output in my page source, as my_localized_data.layout_config becomes a String “Array”, here is the output:
<script type="text/javascript">
/* <![CDATA[ */
var wpkit_localized_data = {
layout_config: "Array"
};
/* ]]> */
</script>
So.. How can I do this (or do I just have to accept that I must ‘flatten’ my object into discrete vars like:
lc_header="1";
ls_ls_sb1 = '1';
etc...