Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Use wp_localize_script, It Is Awesome

Posted on May 27, 2012 by Pippin in Tutorials, Working with jQuery, Writing Plugins 25 Comments
Home» Tutorials » Use wp_localize_script, It Is Awesome
Tweet
Love It - 5

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.


Related Items
  • Making PHP Variables Available to Your JS
Tweet Follow @pippinsplugins
jquery, Michael Martin, Scripts, wp_enqueue_scripts, wp_localize_script

25 comments on “Use wp_localize_script, It Is Awesome”

  1. Paul says:
    May 27, 2012 at 5:55 pm

    yeah, it’s a great technique. I’m using it heavily on a plugin I’m working on. I use it with json_encode, and then jQuery parseJSON to use WordPress settings as objects..
    didn’t know about the array for passing multiple variables though. that’s a nice tip

    Reply
    • Pippin says:
      May 27, 2012 at 6:48 pm

      Oh, that’s a great idea for passing plugin settings.

      I use it most commonly for passing the admin ajax URL to my JS.

  2. Michael Martin says:
    May 28, 2012 at 3:09 pm

    Great post Pippin. It’s really good to see this technique explained fully. It’s not something you come across easily, but once you’ve tried it out, you start to wonder how you ever did without it before.

    And thank you for the post link! :D

    Reply
    • Pippin says:
      May 28, 2012 at 4:29 pm

      I can’t imagine not using this function in just about every plugin I write.

      Thanks for stopping by :)

  3. Gerasimos says:
    May 29, 2012 at 6:37 am

    wp_localize_script() is a powerful little thing. We usually use it to pass parameters from our options panel to jQuery sliders mostly located on homepages.

    Reply
  4. Junior Godoi says:
    May 31, 2012 at 3:45 pm

    What a nice tip!!! Thanks for that, you rock!

    Reply
  5. WPexplorer says:
    June 1, 2012 at 11:00 am

    Glad you wrote about it ;)

    Reply
  6. karthi says:
    June 2, 2012 at 4:30 am

    Thanks!! it’s simple to understand:-)

    Reply
  7. Greg Turner says:
    June 7, 2012 at 4:11 pm

    Whether you have the data hard coded in jQuery script, or hard coded in php, it is the same difference – it is bad. The data should come from the database and be changeable via a post or a custom post type or some means such as that.

    You can access data from the database via AJAX – but that is probably over kill for most requirements.

    An easier way to do it is with the action ‘wp_head’. In the function tied to this action, get the data from the database, and output a simple script with a function that returns the data, Then in your jQuery you can call the function in the simple script to retrieve the data,

    This way there is nothing hard coded in either php or jQuery.

    Reply
    • Pippin says:
      June 7, 2012 at 4:17 pm

      Greg, there are very, very few scenarios where you should attach an action to “wp_head” for making data available to your Javascript.

      Saying that you should always store data in the database is not really a good way to put it. There is absolutely nothing wrong with have data stored in a variable (not in the database at all), as long as you provide a way to modify / manipulate that data. Most of the time this will be done through add_filter() and apply_filter().

    • Greg Turner says:
      June 7, 2012 at 5:37 pm

      Pippin – Due to my 30+ years as a programmer and software engineer, working on some extremely complex web applications, I disagree with everything you wrote. So I guess we shall have to agree to disagree. Although I will allow for data to be stored in a variable, but that is not how your post put it.

    • Pippin says:
      June 7, 2012 at 6:15 pm

      I have no problem with you disagreeing with me :) However, if you disagree with my post here, then you in general disagree with the ways WordPress does things, as the methods described above are used all throughout WordPress, which is also fine to disagree with.

    • Greg Turner says:
      June 7, 2012 at 6:29 pm

      Yes, I do disagree with bugs that are in WordPress, as well as disagreeing with several design decisions that were made in the creation of WordPress, as well as disagreeing with poor coding styles that are sometimes used. WordPress is far, far from perfect.

    • Pippin says:
      June 7, 2012 at 6:54 pm

      I would never claim that WP is perfect.

      One thing I would point out further about wp_localize_script() is that one of the best uses for it is for performing Ajax functions on the front end. Using the included admin-ajax.php for processing Ajax functions is by far one of the best ways to do it in WordPress, and in order to do that, you have to make the URL to admin-ajax.php available to your JS file, which is what wp_localize_script is for.

  8. Paul says:
    June 7, 2012 at 7:21 pm

    much smarter people than me have been recommending this approach, ( people like Otto who is one of the core developers, and Justin Tadlock ). Here’s a post from 2010 about using wp_localize_script
    http://ottopress.com/2010/passing-parameters-from-php-to-javascripts-in-plugins/

    It is also recommended in the highly acclaimed Professional WordPress development book.
    It also has a performance benefit in that the javascript files being static, they can be cached, whereas dynamically generated scripts cannot

    Reply
    • Pippin says:
      June 7, 2012 at 10:05 pm

      Thanks for the support, Paul :)

  9. Jack says:
    July 26, 2012 at 11:29 pm

    Just implementing my js the correct way in the Sermon Manager plugin. This helped – thanks!

    Reply
  10. Paul says:
    January 6, 2013 at 11:24 am

    Great little tutorial pippin, thanks for that, I’ve seen a couple tuts on using wp_localize_script() which went straight over my head, yours just made getting this right, and more importantly properly understanding it, so easy.

    Cheers.

    Reply
  11. Ron Strilaeff says:
    January 12, 2013 at 11:46 am

    @pippin What is in the file js/pw-script.js ?
    Can if be an included js file that I’d plan on using for other things, like a jquery.ajax call and other jquery ui stuff?

    Thanks, Ron

    Reply
    • Pippin says:
      January 14, 2013 at 9:52 pm

      I’m not sure I understand the question, sorry.

  12. PeHaa says:
    February 28, 2013 at 8:47 am

    Thank you ! You’ve just made my day.

    Reply
  13. John says:
    March 11, 2013 at 9:09 am

    Great Tip. Before I was passing php variables to javascript by doing something like this:
    <?php echo ' var product ='.'"'.$product.'"'.''; ?>

    Thanks!

    Reply
    • John says:
      March 11, 2013 at 9:11 am

      echo ‘ var product =’.'”‘.$product.’”‘.”;

  14. John says:
    March 11, 2013 at 9:12 am

    script tags not posting… duh… of course not!

    Reply
    • Pippin says:
      March 11, 2013 at 9:45 am

      If you wrap the code in PRE tags, it will work :)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Create a Live Search in WordPress with jQuery and Ajax
  • Loading Scripts Correctly in the WordPress Admin
  • Review: Cudazi Scroll to Top
  • Full Screen Background Images Plugin
  • Process Ajax Requests Correctly in WordPress Plugins

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes

Latest Tutorials

  • Storing Session Data in WordPress without $_SESSION (19)

    The term Session in web development refers to...

  • Test Your Plugins with RTL (1)

    Right-To-Left languages are those that...

  • Submitting Your First Pull Request to a WordPress Plugin on Github (5)

    Github is an extremely popular tool for managing WordPress plugins, and one...

Enter your email to receive automated updates when new posts are published

WP Core Contributions

  • [24316]

View the ticket on Trac.

WP Codex Contributions

  • Function: shortcode exists
  • Function: has shortcode
  • Function: shortcode exists
  • Function: shortcode exists
  • Function: has shortcode

View all 41 changes in the Codex.

Latest Tweets

  • Could not fetch Twitter RSS feed.

Topics

campaign monitor add_options_page hook get_user_meta Rémi Corson the_content meta box register_setting Sugar Event Calendar attachments wp_enqueue_script contextual help shortcodes authors Related posts attachment image forms do_action plugin mail chimp login short codes comments recent posts post types apply_filters short code bbpress taxonomies custom post type gallery images Ajax Stripe taxonomy jquery widgets users add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2013 Pippin's Plugins