Passing PHP variables to Javascript with wp_localize_script()

I’ve been using jQuery Backstretch in projects for a long time now. I love it. It’s so simple to use, and works perfectly. To use it on your site, you just:

1. Download the file—regular version or minified version, doesn’t matter which—and put it in your theme files’ /assets folder or /js folder, or wherever you put your scripts

2. Enqueue the Backstretch file in functions.php, like so:

function waterstreet_scripts() {
 wp_enqueue_script( 'backstretch', get_template_directory_uri() . '/js/jquery.backstretch.min.js', array( 'jquery' ), '', true );
add_action( 'wp_enqueue_scripts', 'waterstreet_scripts' );

Have a look at the Codex if those parameters don’t make sense to you.

3. Now that Backstretch is properly included in our theme, we can write our own scripts.js file and set a background image for stretchin’. That file might look something like this:

jQuery(function($) {

Ok, so all that’s cool. We’ve added Backstretch and called it with our own scripts file and told it about the background image we want to use. But have you noticed the problem? I’ve hardcoded the path to the file. I develop locally, so that line in my local file will look lit this:


It’s happened to me about 10,000 times now that I will send a client a first draft of a site and they’ll say — Hey! I though we were going to put an image in the background? So then, I’d need to go in and remove the link to my localhost site and add the the live site url—again, by hardcoding it. It should be easier than this. Good news is that it doesn’t need to be this way!

wp_localize_script() to the rescue!

To make a long story short, I just want to be able to use something like site_url(); in my Javascript file so I don’t have to hardcode the url every time—but, of course, I can’t. What I can do, however, is set site_url as a parameter in PHP that I can use in my Javascript via wp_localize_script().

Now, that enqueue file will look something like this:

function waterstreet_scripts() {
	wp_enqueue_script( 'backstretch', get_template_directory_uri() . '/js/jquery.backstretch.min.js', array( 'jquery' ), '', true );

/* Make site url available to JS scripts */

$site_parameters = array(
	'site_url' => get_site_url(),
	'theme_directory' => get_template_directory_uri()
wp_localize_script( 'scripts', 'SiteParameters', $site_parameters );

add_action( 'wp_enqueue_scripts', 'waterstreet_scripts' );

And hence, instead of hardcoding the path to the file in the Backstretch file, I can now simply use the parameter I just setup:


wp_localize_script() is extremely handy for this. Any time you need to reference a PHP variable in a Javascript, you can just go back and add it to the $site_parameters array. You will hardcode no more!