post-page

Adding Scripts Properly to WordPress Part 2 – JavaScript Localization

9
responses
by
 
on
May 7th, 2010
in
HOW-TO, WordPress FAQs

When adding scripts to WordPress, you will inevitably run into a small, but painful, issue of localization.

Localizing a plugin or theme is relatively straightforward, but JavaScript presents its own difficulties since we can’t easily call the PHP functions necessary (which is one reason authors embed JavaScript in PHP files).

Since embedding JavaScript in PHP files is never a good technique, we use localization to save the day.

With JavaScript localization, you can use PHP magic to build your localized strings, and then use JavaScript to read/parse those strings. What you do with them is only limited to your imagination.

Furthermore, if you display anything with JavaScript, chances are your users will want the strings to be localized.

Fortunately, WordPress provides the ultra-handy wp_localize_script function.

wp_localize_script

The wp_localize_script takes three arguments:

  • handle
  • object_name
  • l10n

Handle

The handle argument will be the same handle you use for your script name.
For example, if you have a handle of my_script, you would use the same name when calling the wp_localize_script function.

Object_name

The object_name argument is a string that tells WordPress to create a JavaScript object using the name you specify.

It’s important that the string you pass is as unique as possible in order to minimize naming conflicts with other scripts.

For the upcoming example, our object name will be my_unique_name.

l10n

The l10n argument is an array of strings you would like to localize.
Within this array, you will want to take advantage of the __ function.

wp_localize_script Example

For the purpose of this example, let’s create a function called localize_vars and have it return an array.

<?php
function localize_vars() {
    return array(
        'SiteUrl' => get_bloginfo('url'),
        'OtherText' => __('my text', "my_localization_name")
    );
} //End localize_vars
?>

Please note the use of the __() function. It takes in the text we want to localize, and our localization name. This will be the same name you use if you take advantage of localization within WordPress.

The variable SiteURL gives us the http path to our WordPress site, which comes in handy in certain situations.

From another area in our code, we call the localize_vars function:

<?php 
wp_enqueue_script('my_script', plugins_url('your-plugin-name') .'/my_script.js', array('jquery'), '1.0.0');
wp_localize_script( 'my_script', 'my_unique_name', localize_vars());
?>

WordPress then conveniently adds localization JavaScript immediately before our main script is included. Viewing the page source will reveal:

/* <![CDATA[ */
    my_unique_name = {
        SiteUrl: "http://www.mydomain.com",
        OtherText: "my localized text"
    }
/* ]]> */
</script>
<script type='text/javascript' src='http://www.mydomain.com/wp-content/plugins/my_plugin/my_script.js?ver=1.0.0'></script>

With the localize example, you can use PHP magic to add just about anything to your localization object. Hence, no need to ever embed JavaScript within a PHP file.

Now you can call your localized JavaScript variables from your my_script.js file. Here’s an example of an alert:

alert(my_unique_name.SiteUrl);
alert(my_unique_name.OtherText);

It’s really as easy as that. You can now localize JavaScript strings.

Other Localization Techniques

While the wp_localize_script function does great work, it has one inherent flaw: each localized string is on a new line. For plugins that require a lot of localized strings, the size of the page source can easily balloon to unacceptable levels.

To remedy this, we can use two additional localization techniques: one uses JSON, and the other is a custom function.

The JSON Technique

The JSON Technique uses WordPress’ built-in JSON class in order to parse our localized variables.

We would use the same localize_vars function, but would modify the way we queue our scripts.

First, let’s create a helper function that will instantiate the JSON class and spit out our localized variables to screen.

<?php
function js_localize($name, $vars) {
    ?>
    <script type='text/javascript'>
    /* <![CDATA[ */
    var <?php echo $name; ?> = 
    <?php 
    require_once(ABSPATH . '/wp-includes/class-json.php');
        $wp_json = new Services_JSON();
        echo stripslashes($wp_json->encodeUnsafe($vars)); 
    ?>;
    /* ]]> */
    </script>
<?php
}
?>

The js_localize function takes in a $name (our object name) and an array of our localized variables ($vars).

The function then instantiates the JSON class and encodes the variables for output.

Here’s how the code would look when queueing up your scripts:

<?php 
js_localize('my_unique_name', localize_vars());
wp_enqueue_script('my_script', plugins_url('your-plugin-name') . '/my_script.js', array('jquery'), '1.0.0');
?>

Please note that the js_localize function is run before the script is queued.

While this technique does eliminate the newlines and creates cleaner source code, it does have one major flaw. It doesn’t work for all languages.

For example, the Turkish language causes the above technique to crash and burn.

However, if you don’t plan on having additional languages and want localization purely for the ability to access the JavaScript variables, then I would recommend this technique.

A Custom Function

For those wanting to eliminate the newlines caused by wp_localize_scripts, and still have the ability to handle complex languages, then a custom function will have to suffice.

We’ll use the same exact code to queue our scripts, but the js_localize function will change a bit.

My technique is to iterate through the localized variables, save them to an array, and output the array to screen.

<?php
function js_localize($name, $vars) {
    $data = "var $name = {";
    $arr = array();
    foreach ($vars as $key => $value) {
        $arr[count($arr)] = $key . " : '" . esc_js($value) . "'";
    }
    $data .= implode(",",$arr);
    $data .= "};";
    echo "<script type='text/javascript'>\n";
    echo "/* <![CDATA[ */\n";
    echo $data;
    echo "\n/* ]]> */\n";
    echo "</script>\n";
}
?>

It might not be the most poetic thing you’ve ever seen, but it works pretty well, even for those complex languages.

Localization Conclusion

Within this article you learned the how and the why of JavaScript localization.

The benefits of localizing your JavaScript are:

  • No need to embed JavaScript and PHP.
  • Can capture PHP variables without having to load the WordPress environment.
  • Can enable others to translate your JavaScript strings.

You also learned three different techniques to achieve localization.

  • Using wp_localize_script – Recommended for general use.
  • Using JSON – Recommended for non-complex localization and performance.
  • Using a Custom Function – Recommended for complex localization and performance.

This article is an excerpt from Ronald Huereca’s e-book entitled WordPress and Ajax (used with permission).

heading
9
Responses

 

Comments

  1. Konstantin (7 comments.) says:

    Nice post, I learned a lot.

    Is there any way though, to avoid having to write all localized strings in one variable?

    Context would be the TweetMeme Button, where I can’t assign personalized options, the wp_localize_script-way.

  2. Ronald huereca (32 comments.) says:

    Not that I can think of.

    What you could do is write a small script with localization. Queue Your script with TweetMeme as a dependency. Then in your script, do an onload (jQuery is good at this) and do a DOM replacement of the strings you want localized.

  3. Andrew@BloggingGuide (90 comments.) says:

    Thanks for the clear and easy to follow example. Learned a lot from this.

  4. Jason (1 comments.) says:

    This was a great find! Finally a WordPress way to cleanly separate PHP and javascript… Thanks!

  5. Dave Doolin (25 comments.) says:

    I found this after I bought the book! But I wouldn’t have found it without reading through Chapter 3 of WordPress and Ajax.

  6. Tabby (1 comments.) says:

    Javascript is a royal pain for me.. which isn’t great because advertisers like to have “interactive” banners on my site. They tend to break my website themes when I use it in the sidebar though. Is there anyway to contain script in a manner so it doesn’t mess with anything else like that?

  7. Joe Fitz (1 comments.) says:

    Localizing scripts adds a great way for php to insert variables into js. One thing to watch out for here is security. The localized js objects are global in scope and can easily be manipulated in the console. This creates big security risks and you should try to avoid putting sensitive data in there. But one best practice I have come up with, and I’m sure others have as well, is to use the localized object in a closure. So, for the js file you want the localized object to be used in, you should wrap the whole js file in a closure.

    (function(localized_object){
    /* all code goes here */
    })(localized_object);

    This is a self executing function which passes the localized_object in as a parameter. So any code in this object uses a copy and not the global instance. This prevents any chance of tampering.

  8. Anthony (1 comments.) says:

    I have read so many other articles, but this one is really great! Very clear, concise & straight to the point with relevant code examples in PHP & Javascript.

    There is one thing that I think, is worth mentioning. Please read the following excerpt from the official Codex:

    IMPORTANT!: wp_localize_script() MUST be called after the script it’s being attached to has been enqueued. It doesn’t put the localized script in a queue for later queued scripts.

    Reference: http://codex.wordpress.org/Fun.....ize_script

    So if you can include elaborate on the above point & include it within your article, I think that will help many of us about the caveats of using the wp_localize_script().

    Ronald, I really want to thank for putting up such a helpful article! Keep up the good work!



Trackbacks/Pingbacks

  1. [...] Adding Scripts Properly to WordPress Part 2 – JavaScript Localization [...]

Obviously Powered by WordPress. © 2003-2013

page counter
css.php