Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!