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 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;

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

How to ignore Bullet in RSpec tests

Using Bullet during a test can pick up mistakes but also has false negatives; here is an easy way to ignore them

Ruby

How we used Nokogiri to fix a sizing issue in YouTube's oEmbed

At some point, one of our calls to YouTube's oEmbed endpoint was returning videos way too small; we fixed in in our Rails application by using Nokogiri