Accessing PHP variables from within JavaScript under WordPress is so easy it is almost trivial.  Having said that, I didn't know there was a way to do it until I asked on the Wordpress StackExchange site.

I will show you what you need to do by way of an example.  Let us suppose we need the site URL in our JavaScript code.

It is a two step process, the first step is in your PHP;

$data = array('site_url' => __(site_url()));
wp_localize_script('my_script', 'php_data', $data);

So what we have done there is enqueued our script (named here, my_script) and once we have done that we set up our data array. In our case the property is site_url and it's contents are going to be the result of site_url(). Once we have that we can call wp_localize_script, into it we pass the name of our script, the name we want to give our JavaScript object and the data we want to pass in.

Next we want to be able to access the data, so in your JavaScript file you can simply call the following (if you wanted to alert out the site URL!)


Really, really easy and really, really handy!

For more information please see the official reference.

Why not read some more of our JavaScript posts?