Quantcast
Channel: jQuery – LessThanWeb
Viewing all articles
Browse latest Browse all 6

WordPress and Translatable Javascript Strings

$
0
0

Ever wondered on how to make Javascript strings translatable in WordPress theme or plugin? Well I did and it looks like it’s a really easy thing to do.

To make Javascript strings translatable you need to use the function wp_localize_script.

Here’s a simple example on how to do it with custom Javascript file.

First we need to add our custom Javascript file to theme or plugin using wp_enqueue_script.

function javascript_files() {
	//    Adding custom javascript file to theme or plugin
	wp_enqueue_script('some_handle_name', get_template_directory_uri().'/js/javascript.js');

	//    Create array with values that are going to be used in Javascript file itself
	$translations = array('some_name' => __('Some text'), 'another_key' => '1');

	//    This line is the key:
	//    "some_handle_name" should match the wp_enqueue_script handle
	//    "object" can be named anything, will be used in the Javascript file itself to call the value like: object.some_name
	//    $translations is of course the above array with keys and values
	wp_localize_script('some_handle_name', 'object', $translations);
}
add_action('wp_enqueue_scripts', 'javascript_files');

Then in Javascript file, we can simply call the translated values like this:

console.log(object.some_name); // Will output "Some text"
console.log(object.another_key); // Will output "1"

And that’s it. Really simple thing to do.


Viewing all articles
Browse latest Browse all 6

Latest Images

Trending Articles





Latest Images