WooCommerce email notifications: different email recipient for different cities

北城余情 提交于 2019-11-27 07:14:56

问题


I using Woocommerce and actually I receive order notifications only to one email. I would like to receive notifications about orders in 2 different emails depending on customer location:

  • For customer from zone 1 (Germany) I would like to receive the email notifications at
    Mail #1 (mail1@mail.com),
  • For all other zones like zone 2 (Mexico) I would like to receive the email notifications at
    Mail #2 (mail2@mail.com).

I looking for some functions on net, but I was find only funtcions to send to two email adresses, but without any If condition.

What I will need is something like that:

if ($user->city == 'Germany') $email->send('mail1@mail.com')
else $email->send('mail2@mail.com')

Which hook can I use to get this working?

Thanks.


回答1:


You can use a custom function hooked in woocommerce_email_recipient_{$this->id} filter hook, targeting 'New Order' email notification, this way:

add_filter( 'woocommerce_email_recipient_new_order', 'diff_recipients_email_notifications', 10, 2 );
function diff_recipients_email_notifications( $recipient, $order ) {
    if ( ! is_a( $order, 'WC_Order' ) ) return $recipient;

    // Set HERE your email adresses
    $email_zone1 = 'name1@domain.com';
    $email_zone_others = 'name2@domain.com';

    // Set here your targeted country code for Zone 1
    $country_zone1 = 'GE'; // Germany country code here

    // User Country (We get the billing country if shipping country is not available)
    $user_country = $order->shipping_country;
    if(empty($user_shipping_country))
        $user_country = $order->billing_country;

    // Conditionaly send additional email based on billing customer city
    if ( $country_zone1 == $user_country )
        $recipient = $email_zone1;
    else
        $recipient = $email_zone_others;

    return $recipient;
}

For WooCommerce 3+, some new methods are required and available from WC_Order class concerning billing country and shipping country: get_billing_country() and get_shipping_country()
Usage with $order instance object:

$order->get_billing_country(); // instead of $order->billing_country;
$order->get_shipping_country(); // instead of $order->shipping_country;

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Code is tested and works.


Related answers:

  • How to get order ID in woocommerce_email_headers hook
  • Send on-hold order status email notification to admin


来源:https://stackoverflow.com/questions/41940348/woocommerce-email-notifications-different-email-recipient-for-different-cities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!