How to fix translation in multi-language website + WooCommerce + AJAX checkout

How to fix translation in multi-language website + WooCommerce + AJAX checkout

I have been working recently on a multi-language website that is using WooCommerce > 3.5 and for some of the functionalities that were populated or updated with AJAX calls (for example the checkout page content like the payment methods, the terms and conditions, the cart items summary, etc.) the texts were only rendered in the default language, regardless of the user locale settings.

I spent some time debugging and did some research, here is a small and quick fix that did the trick. I added this in my theme functions.php file, but it can be added in a plugin also.

add_filter( 'woocommerce_get_script_data', 'fix_ajax_handler_translation' );
if ( ! function_exists( 'fix_ajax_handler_translation' ) ) {
	/**
	 * Fix the lost translations on AJAX calls made in WordPress >= 5.0 with WooCommerce >= 3.5
	 * on checkout pages for example.
	 *
	 * @param array $params Script data.
	 * @return array
	 */
	function fix_ajax_handler_translation( $params ) {
		$locale = determine_locale();
		$lang   = ( ! empty( $locale ) ) ? strstr( $locale, '_', true ) : '';
		if ( empty( $lang ) ) {
			// Fail-fast, no need to check further. Fall back to the defaults.
			return $params;
		}
		if ( isset( $params['wc_ajax_url'] ) ) {
			$params['wc_ajax_url'] = $params['wc_ajax_url'] . '&lang=' . $lang;
		}
		return $params;
	}
}

Please note that if you use WordPress < 5.0 the native function determine_locale does not exist (it was introduced with 5.0), but you can use as an alternative get_user_locale.

I hope this helps anyone that encounters the same issue.


Support my work! Click the button below


See other tips & tricks