最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to handle translation for texts inside a .js of a WP theme - Stack Overflow

programmeradmin0浏览0评论

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

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.

Share Improve this question edited Sep 18, 2023 at 23:18 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Apr 24, 2017 at 13:36 tikimti-mvrhttikimti-mvrht 2302 silver badges12 bronze badges 8
  • 1 Your confirm("text") should probably be inside the if-statement (if(confirm("text")) { /*code*/ }). I cannot help with the rest, as I have little to no wordpress knowledge. – Pyromonk Commented Apr 24, 2017 at 13:40
  • @Pyromonk No, otherwise the if statement would never be triggered. – Phill Healey Commented Apr 24, 2017 at 13:41
  • 1 @Pyromonk Ah, your message reads as in "inside the if-statement", meaning if the 'if' condition is met. Whereas you meant make it part of the clause itself. eg if(confirm){var confirmation = confirm("Are you sure you want to quit"); } – Phill Healey Commented Apr 24, 2017 at 13:47
  • 1 Sorry, I meant to say if(confirmation){} – tikimti-mvrht Commented Apr 24, 2017 at 13:49
  • 1 no probs @Pyromonk a fiddle is always good for clearing things up. – Phill Healey Commented Apr 24, 2017 at 13:52
 |  Show 3 more comments

5 Answers 5

Reset to default 10

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);

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>

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.

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' );

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;
发布评论

评论列表(0)

  1. 暂无评论