Search code examples
wordpresslocalization

How does __() decide which language to use (WordPress)


I'm using __("english text", "textdomain") in a WordPress theme template.

The base language of the site is English.

I've successfully added a .pot file for German.

If I set the language in Settings, General to German, I get the German translations on the front end no problem.

I'm trying to implement a language selector, so on the front end the site visitor can select a language.

I thought it was just a case of setting the lang attribute in the html tag appropriately. So when the user selects German, I output <html lang="de-DE">. But still __() uses the language from the WordPress admin settings.

I guess I'm approaching this in the wrong way. Does __() only ever use the language set in WP Admin? Or can I force it to use a different translation file depending on what the visitor selects on the front end?

Thanks.


Solution

  • You might need to use the WordPress filter locale https://developer.wordpress.org/reference/hooks/locale/

    You can do something like this in your function.php

    //set desired locale
    add_filter( 'locale', function($locale) {
        if ( !is_admin() ) 
            $locale = "de-DE";
        return $locale;
    });