JavaScript files are a bit more tricky to translate, as they are often read from an external file that cannot contain any PHP code. The solution to this is the wp_localize_script function. When called, this function declares new variables in scripts that have already been queued up to be loaded, and populates these variables with localized strings. Upon execution, the code will be able to access and display the proper text on screen. The following code snippet is an example showing how to use the function:
wp_enqueue_script( 'script_handle' );
$translation_vars = array( 'string_val' =>
__( 'Text to be translated' ) );
wp_localize_script( 'script_handle', 'javascript_object',
$translation_vars );
In the previous code example, a new object called javascript_object will be created inside the script_handle script, with a data member called string_val that contains a translation of the target text in the current WordPress language, if available.