How to force WordPress to temporarily switch locale (using qTranslate)? [closed]

I have a multi-language store running WooCommerce and qTranslate, and am trying to setup multi-language customer emails. The problem is, the “order complete” email gets sent from the admin backend, and it is sent in the language the backend is used in, not in the language that the order was initially made in.

What I’ve got working so far is storing the order locale as a custom field, and plugging my code into WooCommerce’s email sending mechanism. What I need to do now is to dynamically switch the current locale to the one saved in the order data, dispatch the email, and switch it back.

Currently, I’m trying to force locale in a multitude of places, but none of them work. Here’s the current code:

// get order language and its locale from qTranslate config
$order_custom_data = get_post_custom($order_id);
$new_locale = $order_custom_data['Customer Locale'][0];

// save current locale
$old_locale = get_locale();

// set the current locale and send email with it active
setlocale(LC_ALL, $new_locale);
global $q_config, $locale;
$locale = $new_locale;
$q_config['language'] = substr($new_locale, 0, 2);
// dispatch email
global $wc_cle_wc_email;
$wc_cle_wc_email->customer_processing_order($order_id);

// set the old locale back
$q_config['language'] = substr($old_locale, 0, 2);
$locale = $old_locale;
setlocale(LC_ALL, $old_locale);

Debug output shows the current and order locales being read correctly, and a get_locale() call parallel to customer_processing_order() outputs the order locale instead of the current one. But the email generated by the customer_processing_order() call is built with the current language strings instead of those in the order language. Any ideas how to work around this?

2 s
2

And I got it. What was missing was re-loading the text domain for WooCommerce, that was loaded with the current locale at initialization:

// set the current locale and send email with it active
unload_textdomain('woocommerce');
setlocale(LC_ALL, $new_locale);
global $q_config, $locale, $woocommerce;
$locale = $new_locale;
$q_config['language'] = substr($new_locale, 0, 2);
$woocommerce->load_plugin_textdomain();

global $wc_cle_wc_email;
$wc_cle_wc_email->customer_completed_order($order_id);

// set the old locale back
unload_textdomain('woocommerce');
$q_config['language'] = substr($old_locale, 0, 2);
$locale = $old_locale;
setlocale(LC_ALL, $old_locale);
$woocommerce->load_plugin_textdomain();

Some of the calls setting the locale variables are probably redundant and/or simply unnecessary, but this works.

Leave a Comment