Changing your WordPress site language (locale) dynamically

There are some fantastic multilingual plugins for WordPress, however for one client project I needed something far more flexible, as this particular client needed to cater for several countries that each spoke several languages.

In short the client needed to be able to have a multisite instance that had a country and language set as default, and the ability to override the country and language on each page / post.

Building a Multilingual Plugin

If enough people bug me to do it, I may consider releasing the whole thing as a standalone plugin, however the heart of the multilingual plugin I build relies on the locale WordPress filter, and the heart of the plugin resides in the following code snippet:

Tada! Your locale is now set, and your multilingual site should now be switching languages based on your page/site meta.

Matt Watson in Paris, Listening to a Multilingual Translator
Matt Watson in Paris, Listening to a Multilingual Translator

Wait! My WordPress Core Default Translations Are Not Working!

This is an issue I came across, and couldn’t for the life of me figure it out. My theme translated perfectly after I had added the relevant .mo and .po files, however WordPress core default translations (such as the ‘Leave a Reply’ message in the comments template) were not translating.

It turns out the solution was pretty simple! Although I had catered for custom domain translations, I had forgot to put one simple bit of code into my theme: load_default_textdomain().

If I have shaved a couple of hours off of your debugging with that ‘one weird tip’, you are welcome!

By Matt Watson

Wordpress Developer for Hire. Developer, Father, Husband, Blogger - I do great things on the Web.