WordPress doesn’t load correct language mo-file via ajax request

I made a wordpress theme and set it up in two languages (EN and DE). I also made the required mo-files. I defined german as default language in wp-config.php in the beginning. Everything works fine but I have some problems with AJAX requests: It doesn’t load the correct language files.

My scenario:

Read More

I made a Button/Link requesting data via AJAX. Something like this (javascript):

jQuery('#button').click(function(){
 jQuery.ajax({
  url: "http://myexampledomain.com/wp-admin/admin-ajax.php?lang=en",
  data: { action: 'my_action', id : 123 },
  type: "POST",
 }).done(function (data){
  alert(data);
 });
});

As you can see, I am trying to load my information in english (url => ?lang=en). I wrote this code in my functions.php:

add_action("wp_ajax_nopriv_my_action", "my_action");
add_action("wp_ajax_my_action", "my_action");
function my_action(){
 echo __( 'ID nicht gefunden:', 'mytheme' ) . $_POST['id'] ;
 exit;
}

My Problem is, that the alert “ID nicht gefunden:123” pops up although it should be “ID not found:123“.

It seems wordpress is not loading the correct language mo-file.

To fix this I tried the following in my functions.php (but it didn’t work):

add_filter( 'locale', 'my_theme_localized' );
function my_theme_localized( $locale ){
    if ( isset( $_GET['lang'] ) && $_GET['lang']=='en' ){
        return 'en_US';
    }
    return 'de_DE';
}

I also experemented with some plugins: XILI-language, qTranslate and Polylang.
The result is that only qTranslate was able to load the correct language file via AJAX request.
But qTranslate is not the best solution for some tasks I am working on.

I also found a “workaround” to load the correct mo-file by writing the following into wp-config.php:

if(isset( $_GET['lang'] ) && $_GET['lang']=='en')
 define('WPLANG', 'en_US');
else
 define('WPLANG', 'de_DE');

But I don’t like this hack (modifing wordpress core files).

Is there are good solution to make wordpress load the corret mo-file by using $_GET[‘lang’] parameter in the AJAX request? What piece of code do I need in my functions.php? Any other working solutions?

Related posts

Leave a Reply

1 comment

  1. I had the same issue, I put the below code to under <?PHP and It fixed my issue

    load_theme_textdomain( LANG, get_template_directory() . '/lang' );

    LANG is your language file name