Accessing PHP variables from within JavaScript under WordPress

How you can access PHP variables in JavaScript in WordPress

Accessing PHP variables from within JavaScript under WordPress isn’t as complex as you may think. 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 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;

wp_enqueue_script('my_script');
$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!)

alert(php_data.site_url);

Really, really easy and really, really handy!

For more information please see the official reference.


Recent posts View all

Ruby

The best way to test model scopes in Rails

Learn about Rails scopes and how to best test them with both Rspec and Minitest

Ruby

Finding out what called a Ruby method

A quick way to understand what is calling your code using the caller method