2 years ago

#9129

test-img

murni

How to use __() function on PHP function (in backend, not the frontend) and return to ajax call

I have problem with __() function in PHP. In my Wordpress project,I am making an ajax get callback to get translation for a reason that cannot be avoided. During the callback, I and querying from database. For example 'SELECT title from products'. 'title' value is "ABC is easy as 123!"

Then I need to return the value to front end. But it have to be in the user preference language. ie Chinese. So I will have to return it as 'ABC 就像 123 一样简单!' instead.

So far, I have tried _e(), __(), gettext() in the callback function but none of this solve the problem. Testing it on the PHP (as html) page is does not have any problem.

JS code:

function translation(text){
console.log("text=",text);
var res="";
$.ajax({
    url: ajaxurl,
    data: {action:"get_translations",text:text},
    async: false,
    success: function(response) {
        res = JSON.parse(response);
        console.log("res=",res);
    }
});
    
return res;
}

PHP Code:

function get_translations($data){
    $text = _( $data["text"] ); 
    $text = gettext($data["text"]);
    error_log("text = ".$text.";");
    error_log("gettext=".gettext("My Membership").";");
    echo wp_json_encode($text);
}

Edit: I should also mention that the get_translations() PHP function is in theme, not plugin.

javascript

php

wordpress

translation

gettext

0 Answers

Your Answer

Accepted video resources