One of the challenges you will run into, when developing for WordPress, is finding a way to make your data (which is accessed via PHP) available to your scripts. For example, you might have a popup notification that is displayed when someone clicks a button. The message in this popup, in order to be translatable, should be defined via PHP. The question then, is how do you get it into your jQuery? The answer is with the truly awesome wp_localize_script() function.

The wp_localize_script() was one that eluded me for my first two years of WordPress development. I would see references to it, but I couldn’t ever figure out exactly what it did, or how it worked. It wasn’t until I read Michael Martin’s tutorial titled Load Next WordPress Posts With AJAX. He was the first person I had come across that really explained, and demonstrated how the function worked, and what it did.

The gist of the function is that it allows you to take data from PHP and make it available to your Javascript.

Let’s take the example I mentioned a moment ago, with the popup alert, and see how we can use wp_localize_script().

Since we are loading our scripts correctly, we are using wp_enqueue_script() to load our jQuery:

1
2
3
4
5
6
7
<?php
function pw_load_scripts() {
 
	wp_enqueue_script('pw-script', plugin_dir_url( __FILE__ ) . 'js/pw-script.js');
 
}
add_action('wp_enqueue_scripts', 'pw_load_scripts');

The use of wp_enqueue_script() or wp_register_script() is required for wp_localize_script() to work.

Our example jQuery file looks like this:

1
2
3
4
5
jQuery(document).read(function($) {
	$('#pw_button').on('click', function() {
		alert('Hey! You have clicked the button!');
	});
});

These two code snippets assume that we have an HTML button somewhere on our page with an ID of “pw_button”. When that button is clicked, a javascript alert is displayed, like the one below:

The problem that we have here is that our text, “Hey! You have clicked the button!”, is hard coded into our jQuery. Why is this bad? It’s bad because it cannot be translated, but we can get around this by using wp_localize_script().

Usage of the function is actually quite simple. Here is our PHP:

1
2
3
4
5
6
7
8
9
10
11
<?php
function pw_load_scripts() {
 
	wp_enqueue_script('pw-script', plugin_dir_url( __FILE__ ) . 'js/pw-script.js');
	wp_localize_script('pw-script', 'pw_script_vars', array(
			'alert' => __('Hey! You have clicked the button!', 'pippin')
		)
	);
 
}
add_action('wp_enqueue_scripts', 'pw_load_scripts');

The first function parameter is the handle of our Javascript file, which is the same as the first parameter in our wp_enqueue_script() function.

The function is going to create an object that is accessible from our Javascript The name of this object is the second parameter, pw_script_vars

The third function parameter, is an array of variables to pass to our script. Each key in the array will be setup as an item in our Javascript object. In this case, I have only passed one array key, so we will have just one option, but you can have as many as you want. Each variable will be accessible like this:

pw_script_vars.VARIABLE_NAME

Our alert text is accessible like this:

pw_script_vars.alert

If this doesn’t make sense, read just a little further and it will.

Previously, in our jQuery, we hard coded the alert message, but now we can just pass our localized variable, like so:

1
2
3
4
5
jQuery(document).read(function($) {
	$('#pw_button').on('click', function() {
		alert( pw_script_vars.alert );
	});
});

That is really, really cool, if you ask me.

Now what about multiple variables? let’s say, for a moment, that our jQuery contains two alerts, one for each button that is pressed. Because we have two buttons, we want to have two messages, and wp_localize_script() makes this very easy:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function pw_load_scripts() {
 
	wp_enqueue_script('pw-script', plugin_dir_url( __FILE__ ) . 'js/pw-script.js');
	wp_localize_script('pw-script', 'pw_script_vars', array(
			'alert' => __('Hey! You have clicked the button!', 'pippin'),
			'message' => __('You have clicked the other button. Good job!', 'pippin')
		)
	);
 
}
add_action('wp_enqueue_scripts', 'pw_load_scripts');

Our updated jQuery now looks like this:

1
2
3
4
5
6
7
8
9
10
11
jQuery(document).read(function($) {
 
	$('#pw_button').on('click', function() {
		alert( pw_script_vars.alert );
	});
 
	$('#pw_button_2').on('click', function() {
		alert( pw_script_vars.message );
	});
 
});

Is this the first time you’ve seen wp_localize_script()? Do you have questions? Just let me know below in the comments.

  1. Mabi

    Hi Pippin,
    I get this error
    Uncaught TypeError: jQuery(…).read is not a function

    thanks for the nice tutorial

  2. Mabi

    Well yes, that irresponsible is me then.
    I added the code of the post in a plugin. As it seems not the right place, could you suggest where to load the snippets instead?

    • Pippin

      Can you show me what you added?

  3. Mabi

    I corrected the jquery loading error in my environment.

    Then I had to change the code from
    jQuery(document).read(function($) {
    to
    jQuery(document).ready(function($) {

    everything works now.

    • Pippin

      Great!

  4. Mabi

    How do I send back the data to the wp database now?

  5. Rajandran R

    How to retrive the wordpress username and pass it to javascript?

    • Pippin

      You can use get_current_user_id() to retrieve the ID of the currently logged in user and then get_userdata() to retrieve all information about the user. Once you have that, just pass it to wp_localize_script().

  6. jamie

    Thank you! awesome tutorial! You just solved a problem I have had for more than a year! I did not know you could do this and your very well written and very easy to follow tutorial solved my issue. Thank you for posting the link to your tutorial in the codex. That is how I got here. Well done, Tweeted and followed you

  7. Surja Gain

    Thanks for the tutorial, one question though:
    In the statement: ‘alert’ => __(‘Hey! You have clicked the button!’, ‘pippin’)

    What does ‘pippin’ in the value field actually do?

  8. Clayton Collie

    THIS IS SO AWESOME!

    Now I’m passing value from my custom fields on a page template to the js files.

    Can’t thank you enough!

  9. Vasilis

    Hello, thanks for your article.

    What would you suggest to make the variables more manageable from a non-developer colleague?

    Thank you.

  10. Jordan

    What if I want to localize a variable in a template file into a script that I already enqueued in my functions.php file? What is the best way to do this?

    • Pippin

      Could you show me an example to better illustrate what you’re after?

  11. pamela sillah

    The clearest tutorial on this topic on the entire internet! thanks pippin.

  12. Jon Schroeder

    Pippin, thanks so much for posting this. This is by far the clearest explanation I’ve seen on this topic. One question. I was hoping to use this to output the same javascript several times on the same page, but with variables replacing the bits that need replacing. This doesn’t seem to work, though.

    The script is currently being registered in my plugin’s main file, but being enqueued and localized in the template (which does output twice).

    Is there something obvious I’m doing wrong here?

    • Pippin

      Could you show me a copy of the code that’s not working?

  13. kathy

    Thanks for writing such a useful article. I was wondering whether it is possible to use wp_localize_script for to add google conversion code. So I wanted to use something like this:

    wp_enqueue_script(‘google-adwords’, ‘http://www.googleadservices.com/pagead/conversion.js’);
    wp_localize_script(‘google-adwords’, ‘tu_ga_vars’, array(‘google_conversion_id’ => 1111111111, ‘google_conversion_language’ => ‘en’, ‘google_conversion_format’ => ‘3’, ‘google_conversion_color’ => ‘ffffff’, ‘google_conversion_label’ => ‘somerandomlabel’, ‘google_remarketing_only’ => false));

    to achieve this

    /* */

    Obviously this doesn’t work because I am passing an array of variables rather than 6 string variables. Is there a way around this?

    • kathy

      again, to achieve this

      var google_conversion_id = 1111111111;
      var google_conversion_language = “en”;
      var google_conversion_format = “3”;
      var google_conversion_color = “ffffff”;
      var google_conversion_label = “somerandomlabel”;
      var google_remarketing_only = false;

      to be used in script

      http://www.googleadservices.com/pagead/conversion.js

Leave a Reply

Error: Please enter a valid email address

Error: Invalid email

Error: Please enter your first name

Error: Please enter your last name

Error: Please enter a username

Error: Please enter a password

Error: Please confirm your password

Error: Password and password confirmation do not match