How would you go about setting the correct language returned in AJAX calls, when you are not using any plugin?

All other strings in page work fine just by defining WPLANG to a proper locale.

Example:

function lpml_get_quiz_result_callback() 
{

    // do plenty of stuff before this 

    // this is always returned in original english language, even if I setlocale before or load textdomain manually.
    $message = __('Some english defined string', 'my_txt_domain');
    $status = true;

    echo json_encode(array('status' => $status, 'message' => $message));
    die(); 

} 

add_action('wp_ajax_lpml_get_quiz_result', 'lpml_get_quiz_result_callback');
add_action('wp_ajax_nopriv_lpml_get_quiz_result', 'lpml_get_quiz_result_callback');

I checked these questions: q1, q2, but none applies / solves my case. :/

I tried setting locale and loading textdomain before using __() strings in ajax, but to no avail (tried it just before, and also in admin_init hook for DOING_AJAX), both did not work.

setlocale(LC_ALL, $_POST['lang']);

load_theme_textdomain( 'my_txt_domain', get_template_directory() . '/languages' );

Any tips appreciated!

2 Answers
2

I did manage to solve this later on by using WPML, but over time found that WPML is quite bloaty and slow, support not very good, and if you need only 1 language (but original strings for theme are in English and the language you need is not) or perhaps 2, you do not need it. The only thing you need is:

  1. Set LOCALE in your theme .env or wp-config.php. An example would be LOCALE=de_DE or define('LOCALE', 'de_DE') for wp-config.
  2. Have your text domain loaded based on where your .MO files will be (run this in after_setup_theme hook)

load_theme_textdomain( 'your_domain', get_template_directory() . '/languages' );

  1. Set up your locale via filters based on where you set it

/**
* Set locale based on our .env LOCALE
*/
add_filter( 'locale', function($locale) {
if ( !is_admin() && getenv('LOCALE') !== false)
$locale = getenv('LOCALE');
return $locale;
});

Also, I very much recommend https://roots.io/sage/ to start your
theme off, but it is not required.

It provides a nice way to generate your .pot file for translations via Yarn too. Based on that it is quite easy to create .PO files from it for the languages you need and send them for translation and just follow the steps above (dont forget to put .mo file in languages folder, named de_DE.mo based on your LOCALE, and everything works as expected.

Leave a Reply

Your email address will not be published. Required fields are marked *