WPML: Forcing the language in the WordPress admin area

I am writing this as I spent ages trying to find the answer in WPML documentation and forums and couldn’t find it. It was actually very simple.

TL;DR Use the $sitepress->switch_lang($language_code) function to switch the current language in the admin area.

I wanted to create a page in the WordPress admin area that could preview some emails that were being sent out in multiple languages.

I use WPML plugin in my site, to enable multiple languages, and it adds a language switched in the admin bar, as you can see in the screenshot below:

WPML Admin Language Switcher

I assumed that when I included the template it would display in the language that is selected in the switcher. I assumed incorrectly.

Now users can choose a language for their account in the WordPress admin area, that is independent of the site language, the template will get rendered in the user admin language regardless of the language selected in the switcher.

This isn’t very helpful if you are trying to preview templates in different languages.

I needed a way to force the current language that WPML is using, before the template was rendered.

A quick search on Google was not very illuminating. And the WPML docs are very poor.

It took me an hour to find work out what turns out to be very simple to do.

I knew that you could switch the language when you are sending email templates so I started looking there.

WPML provides a ‘switch_lang’ function, which WPML specifies needs to be used inside the ‘init’ hook. But I didn’t want to change the language of the whole request, just for the specific template I’m rendering. Turns out you can use it anyway. 🙂

global $sitepress;
// get_current_language() gets the language code from the admin language switcher.
$sitepress->switch_lang($sitepress->get_current_language());

// now render your template
include 'my/translated/template.php';

// Now switch the language back to the previous one, by calling it with no params.
$sitepress->switch_lang()

And that’s it! Now my template previews are translated in the same language as the WPML admin language switcher, but the admin language remains the same as the User’s selected admin language.

Leave a Reply

Your email address will not be published. Required fields are marked *