Passing PHP Array To JavaScript Using wp_localize_script()

If you are looking for a generic way to pass a PHP variable to JavaScript, please move on. This post is specific to WordPress plugins.

If you don’t know how to pass a PHP variable to JavaScript for your WordPress plugin, go through this very good post by Otto – Passing parameters from PHP to Javascripts in plugins This is a very safe and straightforward way to pass your PHP variables into your JavaScript.

This works perfectly fine if your variable is NOT an ARRAY. So, if you want to pass your PHP arrays to your JavaScript, you’ll have to do a bit more, but it is still pretty much straight forward. Here are the steps –

1. Encode your PHP array using
json_encode()

2. Pass the encoded array to your JavaScript using
wp_localize_script()
3. Parse the JSON encoded data in JavaScript back to a JSON object
Ain’t it simple? Let’s take one example. Here’s how my sample PHP array looks like –
$my_arr = array('my array',
'name' => 'Ronak',
'surname' => 'Gandhi',
'phone' => array(
'home' => 12345,
'office' => 67890),
'hobbies' => array(
'photography',
'programming',
'driving'),
);

Now we need to encode this array into JSON string.
$my_json_str = json_encode($my_arr);
json_encode() serialized PHP arrays into strings. If you print the encoded string, it will look like this –
{"0":"my array","name":"Ronak","surname":"Gandhi","phone":{"home":12345,"office":67890},"hobbies":["photography","programming","driving"]}
Now that our array is a PHP string, we can pass it to JavaScript using wp_localize_script().
$params = array(
'my_arr' => $my_json_str,
);

wp_enqueue_script('my-java-script');
wp_localize_script('my-java-script', 'php_params', $params);

Next step is to parse the JSON string back to a JSON object in JavaScript. Our PHP array passed using wp_localize_script() is available in JavaScript as php_params.my_arr. If you check the string value of php_params.my_arr, you will see lot of quot; amp; etc. So first we need to replace those escaped characters. If you have other such characters in the string, you’d have to replace them too.
/* Before replacement
{"0":"my array","name":"Ronak","surname":"Gandhi
","phone":{"home":12345,"office":67890},"hobbies":["photography","programming","driving"]}
*/

var my_json_str = php_params.my_arr.replace(/"/g, '"');

/* After replacement
{"0":"my array","name":"Ronak","surname":"Gandhi","phone":{"home":12345,"office":67890},"hobbies":["photography","programming","driving"]}
*/

Now we can safely parse this string and convert it into a JSON object.
var my_php_arr = jQuery.parseJSON(my_json_str);

Once this is done, we can access my_php_arr as any other JSON object. Parameters can be accessed as my_php_arr[‘name’], my_php_arr[‘surname’] etc.

Leave a Reply