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.

A Small and Quick Fix
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. Fallback 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 it as an alternative for get_user_locale
.
I hope this helps anyone that encounters the same issue.
If you would like to support my work, consider making a donation, buy me a coffee, or share this on your feed.
A huge thanks in advance!
Are you interested in more programming tips and tricks?
How to Integrate Google reCAPTCHA v3 in Forms that Use AJAX Validation
I recently had to update one of the sites that is…
Brief Introduction to Acceptance Testing
Last month I survived my first public presentation, at Bucharest WordPress Meetup…
Free CSS and HTML Grid Generator – Demo and Code Snippet
This is a useful online tool for both designers and programmers…
How to Automatically Set a Specific Template to New WordPress Posts – Snippet Included
Applying by default a specific…