WPML’s ICL_LANGUAGE_CODE constant always returns the default language within AJAX functions

Find out how to get the currently active language from WPML when using AJAX functions

The WPML plugin offers a useful constant to determine the language that is currently being viewed – ICL_LANGUAGE_CODE. This constant will return the language code, usually two characters, of the current language according to the ‘code’ defined under WPML’s Languages settings.

However, if you’re writing AJAX functions within your WordPress site, you will find that ICL_LANGUAGE_CODE always returns the code of your default language, rather than whatever language is currently being viewed. Fortunately, the solution to this is straightforward and relies upon a setting within the WPML plugin settings.

Within the WordPress admin area, navigate to WPML and the first subsection, Languages. Scroll down until you find an option labelled ‘Language filtering for AJAX operations’. Check the option to ‘Store a language cookie to support language filtering for AJAX’ and WPML will drop a cookie named wp-wpml_current_language when a visitor first lands on your website or whenever they navigate to a page in a different language.

With that language cookie option checked in WPML, you’ll discover that ICL_LANGUAGE_CODEwill return the current language rather than the default value whenever you print it or use it in a conditional statement within your WordPress AJAX functions.

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones