Translate emails into the language of the user
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 [email protected]', 'Reply-To: [email protected]', '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.