I need to check what language is currently being displayed on my WordPress site that uses the Polylang plugin. I want to run different code based on which language the visitor is viewing. For example, I might want to show different content or change some functionality depending on the language.
I’m looking for a way to get the language code so I can use it in conditional statements like this:
if($active_language == "fr") {
// Display French-specific content
echo "Bonjour!";
} else {
// Default content
echo "Hello!";
}
What’s the proper method to retrieve the current language identifier from Polylang? I’ve tried looking through the documentation but I’m not sure which function or variable I should be using.
To retrieve the current language code in WordPress using the Polylang plugin, you can use the function pll_current_language(). This function will return the active language code, which you can then use in your conditional statements as follows:
$current_lang = pll_current_language();
if($current_lang == 'fr') {
echo 'Bonjour!';
} else {
echo 'Hello!';
}
I’ve implemented this in various multilingual setups, and it reliably provides the right output. Just ensure it’s executed after the init hook to avoid issues.
You can also use pll_current_language('locale') if you need the full locale instead of just the language code. This gives you ‘fr_FR’ instead of ‘fr’, which is handy for specific localization stuff like date formats or currency displays that change by region. I’ve found this really helpful for that kind of work. There’s also pll_current_language('name') to get the language name in its native form, but for conditional logic you’ll usually want the standard pll_current_language() without parameters since it gives you the clean two-letter code.
heads up - pll_current_language() can return null if Polylang hasn’t loaded yet. i wrap it in if(function_exists('pll_current_language')) to avoid errors. you can also use get_locale() as a fallback when Polylang isn’t active on certain pages.