Skip to content

How to set the WPML language locale of an AJAX call

Enable WordPress AJAX requests to set the language locale through WPML with this small patch.

An issue that I’ve encountered in WPML is the inability to set the language locale during an AJAX call hooked through admin-ajax.php. Upon inspecting the source, I’ve noticed that there is some infrastructure for receiving a language parameter and setting the language locale as such but currently [WPML 3.1.4] there is an oversight that clobbers the received parameter with the admin default. What does the admin default have to do with this? A caveat of WordPress AJAX functionality, the request is treated as an admin page request.


A viable solution requiring little effort entails modifying the admin language and then letting that clobber the language locale of the AJAX request. As such, the field that controls the admin language setup is a private member so a little dirty work is needed. I’ve written a small hook that uses Reflection to access and set said private member with the passed language parameter. I also check to make sure that it’s not an internal AJAX call made by WPML itself, marked by an icl_ajx_action parameter.

To simplify deployment, I recommend saving this into some wpml-patch.php file and placing it in wp-content/mu-plugins/ to autoload the code as an MU plugin and not have to manage it through the plugin manager.

add_action( 'plugins_loaded', function() {
  global $sitepress;
  if( wp_doing_ajax() && !isset( $_REQUEST['icl_ajx_action'] ) && isset( $_POST[ 'lang' ] ) ) {
    $reflection = new ReflectionClass( 'SitePress' );
    $admin_language = $reflection->getProperty( 'admin_language' );
    $admin_language->setAccessible( true );
    $admin_language->setValue( $sitepress, $_POST[ 'lang' ] );
} );