Wordpress admin-ajax and user profile localization

475 Views Asked by At

So I've got an English-language theme that I localized to Spanish. It works perfectly fine in Spanish.

But if I change my user profile language to English - so that I can see English on the dashboard - the AJAX-generated content on the site becomes untranslated English.

If I log out, the AJAX-generated content becomes Spanish again.

My guess here is that admin-ajax is loading the USER profile language instead of the theme language, if the user profile language is set.

So my question is: how can I correct this, so that admin-ajax always uses the theme language?


Edit: here's the AJAX call. I'm not sending any text to be translated.

$('#load_more').on('click', function() {
    var offset = $('#main-ajax-container').data('offset');
    var prefix = $('#main-ajax-container').data('prefix');
    var blogid = $('#main-ajax-container').data('blogid');
    var fid = $('#main-ajax-container').data('fid');

$.ajax({
  type: "get",
  url: "wp-admin/admin-ajax.php",
  data: {
    action: "home_load_more",
    siteUrl: "<?php echo get_site_url();?>",
    offset: offset,
    prefix: prefix,
    blogid: blogid,
    fid: fid
  },
  success: function(resp) {
      $('#main-ajax-container').append(resp);
      offset = parseInt(offset) + 3;
      $('#main-ajax-container').data('offset', offset);
      var max = $('#main-ajax-container').data('max');
      if (offset >= parseInt(max)) { 
        $('#load_more').addClass('done');
      }
    } 
  });
});
1

There are 1 best solutions below

0
On

You're right about the reason. As indicated by its name, the "admin-ajax" endpoint is part of the admin area, so the "dashboard" language will be used.

I assume that you're using the Ajax endpoint for non-admin purposes, but the question is what content you are loading via Ajax?

The simplest case is that you're loading only your theme translations. This case makes it easy to override the "theme language" as you say.

Try adding this into your theme's functions.php file:

if( defined('DOING_AJAX') && DOING_AJAX && is_user_logged_in() ){
  add_filter('theme_locale', function(){
    return get_locale();
  } );
}

However, you ask how to make admin-ajax always use the site language. Is this really what you want? This would mean that any ajax functions being used anywhere in the dashboard would not be in the same language as the page they're running in.

There are ways to do that, but it gets more complex. If you update your question in that respect, I'll update my answer.