How to change the WordPress language on the fly

How to change the WordPress language on the fly


If you need to change the WordPress language on the fly, based on some conditions to be checked when the page is loaded, you need to write a small plugin to be fired at the right time.

In ancient times the WordPress language was defined in the wp-config.php file by this line

define( 'WPLANG', 'it_IT' );

Now, from version 4.0, there is a database option for this that you can tune from the Settings General Screen.

To change the value on the fly, during the page loading, you need to use the locale filter.

This is an example implementation.

function miczit_change_lang ( $lang ) {
//do your stuff and return the right locale or return $lang if you do not want to change it
    $my_locale = decide_the_locale_to_use();
    return $my_locale;

function miczit_plugin_setup(){
    add_filter( 'locale', 'miczit_change_lang' );
add_action('plugins_loaded', 'miczit_plugin_setup');

The trick is to add the filter in a function called by the plugins_loaded hook. If you add the filter later, it won’t work.
The function decide_the_locale_to_use() has to contain all the logic needed to choose the locale you want to use.

Remember that if you are using a caching system, you need to store different versions of the same page to be served depending on the condition.
To achieve this, you need to check the features of your caching plugin.

If you’re using WP Super Cache, you can read this tutorial.


For the image thanks to

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.