Wordpress doesn't load correct language mo-file via ajax request


Staff member
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:

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

  url: "http://myexampledomain.com/wp-admin/admin-ajax.php?lang=en",
  data: { action: 'my_action', id : 123 },
  type: "POST",
 }).done(function (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'] ;

My Problem is, that the alert "<strong>ID nicht gefunden:123</strong>" pops up although it should be "<strong>ID not found:123</strong>".

<strong>It seems wordpress is not loading the correct language mo-file.</strong>

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'] ) &amp;&amp; $_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'] ) &amp;&amp; $_GET['lang']=='en')
 define('WPLANG', 'en_US');
 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?