Localization using JavaScript within WordPress

Posted on July 7th, 2011

Creating Plugins and Theme functions with multilanguage capability has been established knowadays. There may be some difficulties while 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:

    $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.