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.
Hi Pippin,
I get this error
Uncaught TypeError: jQuery(…).read is not a function
thanks for the nice tutorial
That usually means something on your site is loading jQuery improperly. See this post: https://pippinsplugins.com/why-loading-your-own-jquery-is-irresponsible/
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?
Can you show me what you added?
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.
Great!
How do I send back the data to the wp database now?
How to retrive the wordpress username and pass it to javascript?
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().
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
This is awesome, you totally opened my eyes. Thanks
This was a fantasitic explanation! Thank you
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?
That is the text domain that is used for translation purposes: https://codex.wordpress.org/I18n_for_WordPress_Developers
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!
Hello, thanks for your article.
What would you suggest to make the variables more manageable from a non-developer colleague?
Thank you.
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?
Could you show me an example to better illustrate what you’re after?
The clearest tutorial on this topic on the entire internet! thanks pippin.
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?
Could you show me a copy of the code that’s not working?
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?
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
I’ve a plugin Called Post Status Notifier. https://wordpress.org/plugins/post-status-notifier-lite/ . Every time I add this my host complains that there is a malware or virus as it writes to functions.php the mail scripts to send when a new front end post is created.
Can we use this functionality wp_localize_script for the localisation a website?
Instead of a JavaScript object, is it possible to replace it with a data/text file?
Thanks for a great post. I was about to delete a call to this function because I didn’t care about local languages for a particular script, but then read your post and figured that it was not passing language data; it was passing other useful data. Thanks again 🙂
Thank you very much for your post.it so amazing.keep it up
I have just try this
Regards
Sradha
Thanks for sharing your thoughts on pot’s.
Regards
I think you should explain what the ‘pippin’ is in your article, not just in a reply to someone’s comment. I spent 20MIN trying to figure it out. Why would you leave this out?
Is it ok to pass a permalink(url) through localize_script and then use it in your js? Or would that pose a security threat?
As long as it’s a link that’s fine to share publicly, that won’t pose any problems.
i making datatable server side wordpress it not giving any output anyone can help
‘localhost’,
‘user’=>’root’,
‘pass’=>’123@abc’,
‘db’=>’wordpress’
);
$table=’wp_form’;
$columns=array(
array( ‘db’ => ‘name’, ‘dt’ => 0 ),
array( ‘db’ => ’email’, ‘dt’ => 1 ),
array( ‘db’ => ‘salary’, ‘dt’ => 2 ),
array( ‘db’ => ‘mno’, ‘dt’ => 3 ),
);
$json_data = array(
“draw”=> intval( $_REQUEST[‘draw’] ),
“recordsTotal” => intval( $total_records ),
“recordsFiltered” => intval( $total_records ),
“data” => $columns
);
header(‘Content-Type: application/json’);
echo $json_data;
wp_die();
}
add_action( ‘wp_ajax_add_data_handler’, ‘add_data_handler’ );
add_action( ‘wp_ajax_nopriv_add_data_handler’, ‘add_data_handler’ );
}
?>
Hi, tell me is the use of the wp_localize_script function in search.php correct?
Thanks for the explaination. This is by far the clearest explaination of what must be the stupidest design ever for passing info from WP to Javascript.
Btw did you mention WHERE to put the php code ??