Setting Email locale before retrieving gettext translations

What I now want to be able to do is set the locale for a function call
of __(), to retrieve the translation you defined on your plugin’s
.mo for a translation which is different from the current locale.

I’d prefer my translations to be translated all in the same way, using
the same logic provided by wordpress. Hence I’d like to use an
approach via the __(), if possible.

__(), _e(), _n() and other core translation/gettext functions do not have a parameter for setting the locale, but just like how wp_new_user_notification() did it, you can use switch_to_locale() to manually (and just temporarily) switch to the target locale (like English in your example, which is a user-defined locale) and then just call __() or the relevant function to retrieve the translation in the locale which you’ve just switched to.

So for example, you would do:

$switched_locale = switch_to_locale( get_user_locale() );
// Or explicitly specify the locale:
//$switched_locale = switch_to_locale( 'of-this-locale' );

$foo = __( 'get-this-translation', 'of-this-text-domain' );
error_log( $foo );
// or do whatever necessary..

if ( $switched_locale ) {
    restore_previous_locale();
}

Update

Note that you need to re-load your plugin’s translations after you’ve switched to a different locale and also after you’ve restored the original/previous locale.

So you would call load_plugin_textdomain() or load_muplugin_textdomain() like this:

// So in your main plugin file, you might have something like:
add_action( 'init', 'your_plugin_load_textdomain' );
function your_plugin_load_textdomain() {
    load_plugin_textdomain( 'your-domain', false,
        dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}

// Then wherever you want to switch the current locale, call the above function
// to re-load the plugin's translations.
if ( $switched_locale = switch_to_locale( get_user_locale() ) ) {
    your_plugin_load_textdomain(); // call it here

    // do your gettext stuff, e.g.
    _e( 'Hello World!', 'your-domain' );

    restore_previous_locale();
    your_plugin_load_textdomain(); // and then here
}

And if you want, you can try my plugins below to test the above functions (switch_to_locale() and restore_previous_locale()):

  • WPSE 393178 DE — this plugin used German as the main/base language and the plugin came with two MO files, namely wpse-393178-de-en_US.mo and wpse-393178-de-fr_FR.mo.

  • WPSE 393178 EN — this plugin is essentially the same as the one above, except that the main language is English, and the MO files are wpse-393178-en-de_DE.mo and wpse-393178-en-fr_FR.mo.

So I hope that helps and to check whether the localization works correctly, just set your site or profile language to the opposite of the main language of those plugins and visit the plugin admin page (at wp-admin → Tools → “WPSE 393178 DE/EN”). (Both plugins can be activated at the same time)