I am working on sending email notifications in the language in which the order was placed, using Polylang. Currently, my email notifications are sent in the language of the user who triggered these emails (e.g. admin, shop manager).
I have written the code below, and I am confident that the functions map_language_to_locale()
and get_locale_from_order_id()
work correctly. The issue seems to be with this part of the set_email_locale_based_on_order()
function: $order_id = $email->object->id;
. When I run the set_email_locale_based_on_order()
function with $locale = 'pt_BR';
, the email notification is correctly sent in the language in which the order was placed.
Anyone knows how to solve this?
<?php
add_filter($hook_name = 'woocommerce_allow_switching_email_locale', $callback = 'set_email_locale_based_on_order', $priority = 10, $accepted_args = 2);
add_action($hook_name = 'woocommerce_email_footer', $callback = 'restore_email_locale', $priority = 10, $accepted_args = 1);
function map_language_to_locale($language_slug)
{
// Define a mapping of language slugs to locale codes
$mapping = array(
'de' => 'de_DE',
'en' => 'en_US',
'pt' => 'pt_BR',
);
return isset($mapping[$language_slug]) ? $mapping[$language_slug] : false;
}
function get_locale_from_order_id($order_id)
{
if (function_exists('pll_get_post_language')) {
$order_language = pll_get_post_language($order_id, 'slug');
return map_language_to_locale($order_language);
}
return null;
}
function set_email_locale_based_on_order($email_locale, $email)
{
// error_log('Email Object: ' . print_r($email, true));
$order_id = $email->object->id; // Get the order ID from the email object
$locale = get_locale_from_order_id($order_id);
// $locale = 'pt_BR'; // If I run this, it works
switch_to_locale($locale);
// Log the locale switch
error_log("Switched to locale: " . $locale);
// Filter on plugin_locale so load_plugin_textdomain loads the correct locale.
add_filter($hook_name = 'plugin_locale', $callback = fn () => $locale);
return $email_locale;
}
function restore_email_locale()
{
restore_previous_locale();
}
2
Answers
I was able to solve this issue. I have also included emails for shipping and invoice for the "Germanized for WooCommerce" plugin.
There are some modifications needs to be made in order to make sure we are properly
handling
theemail object
to get theorder ID
. Also ensure thelocale switching
andrestoring
are correctly handled. We need to adddebugging logs
to identify where the issue might be.