1

The following scenario: An admin activates a function or similar for a user (in the WordPress frontend). Now the user should be informed about this by email. Therefore an AJAX call is sent to the WordPress backend. There, the mail should be sent in the language set by the user.

Here is my code for this:

add_action('wp_ajax_handle_action', 'handle_action');
function handle_action(){
    $username = $_POST['username'];
    $user = get_user_by('login', $username);
    $user_id = $user->ID;
    $email = $user->user_email;
        // To check if user lang is set correct; it is set to 'en'; all good
    $lang = get_user_meta( $user_id, 'icl_admin_language', true );
    // Switch language to user language
    $locale_switched = switch_to_locale( get_user_locale($user_id) );

        $subject = __('Mein Betreff', 'mydomain');
        $message = __('Nur ein Test', 'mydomain');
        $headers = array('From: John <john@test.de>', 'Reply-To: john@test.de', 'Content-Type: text/html; charset=UTF-8');

        wp_mail( $email, $subject, $message, $headers );

        if ( $locale_switched ) {
        restore_previous_locale();
    }
        echo 'success';
        die();
}

But unfortunately the mail is sent in German. The strings are not translated, although there are translations for these strings (which also work correctly elsewhere, for example, when the user calls up a page in their own language).

What am I missing? Why are the strings not translated into the user's language?

Many thanks for your opinion!

Edit:

Of course i load the domain in my plugin as well:

function my_plugin_load_plugin_textdomain() {
    load_plugin_textdomain( 'mydomain', FALSE, basename( dirname( __FILE__ ) ) . '/' );
}
add_action( 'init', 'my_plugin_load_plugin_textdomain' );

Edit 2:

When i do not switch the locale, the strings get translated in the current website language (de_DE). But when i add

$locale_switched = switch_to_locale('en_US');

the strings do not get translated at all. Not in german (de_DE) and not in English (en_US). switch_to_locale seems to kill my translations completely. Although get_locale returns the right value (en_US) nothing gets translated.

I am lost.

4
  • Are those standard translations, or are they translations provided by a translation plugin?
    – Tom J Nowell
    Aug 7 '21 at 21:04
  • These are .mo and .po files generated with Loco Translate.
    – Farley
    Aug 8 '21 at 10:51
  • is the locale of that user en_US? Is this issue for all locales or specific locales?
    – Tom J Nowell
    Aug 8 '21 at 11:23
  • In this case it is 'en'. But i tested with 'hr' as well. Same behaviour: Strings are not translated.
    – Farley
    Aug 8 '21 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.