Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda