Change Locale Dynamically in WordPress

Discover how to quickly change the locale ISO code at runtime in WordPress without having to access the configuration settings or the administration console.

What is the locale ISO code?

The locale code are used by search engines and your Internet browser to interpret the display language used in the current web page. The language code is particularly important at SEO level since it tells robots the language of indexing in search engines. It is also very important at user experience level since it tells to your Internet browser software how to interpret and display the characters properly.

Why change the locale code at run time?

This PHP code is especially useful when you do not have access to all the WordPress settings such as the Dashboard and plugins when your site is hosted in a multisite environment. But you should have the rights to modify the code in the functions.php file of your theme.

PHP code to change the locale code at run time

Here is the PHP code that allows you to change the WordPress locale ISO code. Simply copy and paste this PHP code into the functions.php file of your WordPress theme and you're done.


PHP Code Features

  • language_attributes Filter : We change the locale ISO code on the fly for the <html> and the <link hreflang=...>, just before they are displayed using the WordPress filter language_attributes.
  • locale Filter : Finally, we change the locale ISO code for the social tags <og:...> at runtime, right before being displayed by using the WordPress filter locale.
  • English Canada Code : We replace the English - US local en-US by the English - Canada local en-CA.