Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda