tikimti-mvrht
tikimti-mvrht

Reputation: 230

How to handle translation for texts inside a .js of a WP theme

I have a WordPress application and usually I use the PHP function <?php _e('foo', 'bar') ?> when I need to echo something that needs to be translated. But, right now I am implementing a new feature and in my .js file I have something like

var confirmation = confirm("Are you sure you want to quit"); 
if(confirmation){
 ... 
}

The problem with the above code is that I can't use the PHP function _e() to translate it since this a JS script.

Is there anyway to enable translation for texts echoed in JS?

Update

I am adding an update, since the questions given are generic whereas I am searching for a solution that can solve my issue.

I am working on WP project that was built by someone before. I am supposed to only add a translation to codes that exist in js file called functions.js path: C:\Users\meskerem\foo.com\wp-content\themes\foo\assets\scripts\functions.js let's assume the following code exists inside the function.

var confirmation = confirm("Are you sure you want to quit"); 
if(confirmation){
 ... 
}

Now the objective is make that English sentence translatable. The above js code is executed when a button inside this file is clicked. C:\Users\meskerem\foo.com\wp-content\plugins\wp-jobhunt\templates\dashboards\candidate\templates_ajax_functions.php

The HTML code that triggers the translation is as simple as:

<h1> <?= _e('good morning', 'jobhunt') ?> </h1>
<div> <i class='icon-trash' onclick="askConfirmation()"> x </i> </div>

So, the script is simple but translating is where I have some issues.

Upvotes: 22

Views: 4833

Answers (5)

delboy1978uk
delboy1978uk

Reputation: 12375

Make a simple PHP script your JS can call via AJAX which does nothing more than translate a string, (or several strings) sent through HTTP GET and echo it out as the response body (probably with json_encode()).

Then you can create a JS function for making that AJAX call, so calling it could be as simple as calling a JS function

var confirmTxt = jstranslate('Are you sure you want to quit?');

And using JQuery for example:

function jstranslate(string)
{
    translations = $.get('/my-ajax-translate-url',{string: string}, function(e){
        return e.text; // console.log e to double check what to return, this is from memory
    });
}

And In PHP

// require_once() your _e() function.
$text = _e($_GET['string'], 'jobhunt');
header('Content-Type: application/json');
echo json_encode(array('text' => $text));
exit;

Upvotes: 1

Learnator
Learnator

Reputation: 47

maybe this could help

function addScript() {
    wp_enqueue_script( 'functions', get_template_directory_uri() . 'foo\assets\scripts\functions.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'addScript' );

Upvotes: 2

Danijel
Danijel

Reputation: 12709

If I understood the problem correctly, you have a script that is enqueued by a third party plugin or theme, and you want to localize the window.confirm box without modifying the original scripts.

/wp-content/plugins/jobhunt-client-translations/jobhunt-client-translations.php

<?php
/*
Plugin Name: Jobhunt Translations
Author: John Doe
*/

add_action( 'wp_enqueue_scripts', function() {

    wp_enqueue_script( 'translations', plugins_url( '/translations.js', __FILE__ ) );

    // change the translations domain from 'default' to match yours
    // you can also add other translations here in format "message" => "translated message"
    wp_localize_script( 'translations', 'DialogMessages', [ 'Are you sure you want to quit' => __( 'Are you sure you want to quit', 'default' ) ] );

});

/wp-content/plugins/jobhunt-client-translations/translations.js

(function( original ) {
    window.confirm = function( message ) {
        message = DialogMessages[message] || message;
        return original.call( this, message );
    };
})(window.confirm);

Create new folder jobhunt-client-translations in /wp-content/plugins/ directory, place inside these the two files, and activate the plugin. It will simply override default window.confirm dialog without changing any of the original third party files, and without modifying the default behavior of the dialog box except that message will be translated.

The code was tested and it works properly.

Upvotes: 2

Ashish Patel
Ashish Patel

Reputation: 3614

In word press you have to pass translation array to respective java script.

for example,

if you are en queue script like below from function.php file,

wp_enqueue_script( $handle, $src, $deps,$ver,$in_footer );

you have to add translation from function file to perticular js by use his handle inside wp_localize_script();

  e.g. wp_enqueue_script( 'your-handle', $src, $deps,$ver,$in_footer );

  $translation_array = array('messagekey' => __('Are you sure you want to quit', foo');                             );
  wp_localize_script('your-handle', 'langvars', $translation_array);

In your case

wp_enqueue_script( 'cs_functions_js', plugins_url('/assets/scripts/functions.js', __FILE__ ), '', '', true );

just add below code after above code.

$translation_array = array('messagekey' => __('Are you sure you want to quit', foo');                                );
  wp_localize_script('cs_functions_js', 'langvars', $translation_array);

Then you can access translation in js like,

var confirmboxmessage = langvars.messagekey;
var confirmation = confirm(langvars.messagekey);

Upvotes: 10

Phill Healey
Phill Healey

Reputation: 3180

You should use the wp_localize_script function, which was added to WordPress for this very reason.

Try with something like this:

wp_localize_script( $handle, $name, $data );

Example

<?php

// Register the script
wp_register_script( 'some_handle', '<ENTER YOUR SCRIPT PATH HERE>' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

You can access the variables in JavaScript as follows:

<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script> 

Note: The data in the resulting JavaScript call will be passed as text. If you are trying to pass integers you will need to call the JavaScript parseInt() function.

<script>
// Call a function that needs an int.
FinalZoom = map.getBoundsZoomLevel( bounds ) - parseInt( object_name.a_value, 10 ); 
</script>

Upvotes: 8

Related Questions