Localization with JavaScript in WordPress

Creating Plugins and Theme functions with multilanguage capability has been established knowadays.Especially for us as German developers it is a must have. But there are some difficulties if you are using JavaScript, the question is how to provide it multilingual or provide option values in different languages. WordPress offers some possibilities and I like to show them, since this question was asked by many and developers are searching for solutions. The following little example should show the realization and the easy output of strings demonstrates it. Wether strings for multilanguage or providing options values, it doesn’t matter.

First we create a function with an array that contains the required content and can be accessed on the relevant content using variables.

function get_language_strings() {
    $strings = array(
        'example' => __( 'My Example String', TEXTDOMAIN_CONSTANT ),
        'foo'   => __( 'My foo string', TEXTDOMAIN_CONSTANT ),
        'bar'   => __( 'My bar', TEXTDOMAIN_CONSTANT )
    )

    return $strings;
}

When you call the extension, Plugin or Theme, the function must be loaded. For this task WordPress provides the function wp_localize_script() that takes care of everything:

wp_localize_script( 
                       'my_foo', 
                       'my_var_prefix',
                       $this->get_language_strings() // inside class
);

You can access the variables in the scripts:

alert( my_var_prefix.example );

No integration of wp-load.php or something like this, simply access the content. The strings are now translated into all languages using the classical methods and it applies only to create the appropriate files.


Posted

in

by

Comments

4 responses to “Localization with JavaScript in WordPress”

  1. John P Bloch Avatar

    That’s a great little tool there.

    One thing that’s not quite right in your example, there: The first argument of wp_localize_script is the id of the javascript you’re localizing, as defined in wp_enqueue_script. That way, WordPress knows that your localization is a dependency of that script and will be printed before that script. So if script foo.js was registered like this:

    wp_enqueue_script( 'myFoo', 'http://example.com/foo.js' );

    You would localize it like this:

    wp_localize_script( 'myFoo', 'my_var_prefix', $this->get_language_strings() );

    That way, when it’s all printed out, It’ll be in the correct order:

    <script>//your localized strings here</script>
    <script src="http://example.com/foo.js"></script>

  2. Frank Avatar

    @John: thanks for this comment and you have right; sorry- now i have fixed the example source.

  3. John P Bloch Avatar

    Happy to lend my knowledge!

    😀

  4. Frank Avatar

    Happy to read my posts and correcting my mistakes. Thats is the true size of WP – the community.