在Woocommerce中取消订单后向客户发送电子邮件

8

我想在订单被取消时向客户发送电子邮件。默认情况下,WooCommerce只会将此电子邮件发送给网站管理员。以下代码已解决相关网页上类似的问题:

function wc_cancelled_order_add_customer_email( $recipient, $order ){
   return $recipient . ',' . $order->billing_email;
}
add_filter( 'woocommerce_email_recipient_cancelled_order', 'wc_cancelled_order_add_customer_email', 10, 2 );
add_filter( 'woocommerce_email_recipient_failed_order', 'wc_cancelled_order_add_customer_email', 10, 2 );

然而,看起来 WooCommerce 已完全删除了那些筛选器钩子。有没有其他方法可以实现这个功能呢?
提前感谢!
1个回答

37
在这个自定义函数中,我针对“取消”和“失败”的订单,通过 woocommerce_order_status_changed 动作钩子,向客户发送相应的电子邮件通知(因为管理员将通过 WooCommerce 自动通知在他的侧面收到它):
```

使用 woocommerce_order_status_changed 动作钩子的自定义函数中,我针对“取消”和“失败”的订单发送了相应的电子邮件通知给客户(管理员将通过 WooCommerce 自动通知在他的一侧收到它):

```
add_action('woocommerce_order_status_changed', 'send_custom_email_notifications', 10, 4 );
function send_custom_email_notifications( $order_id, $old_status, $new_status, $order ){
    if ( $new_status == 'cancelled' || $new_status == 'failed' ){
        $wc_emails = WC()->mailer()->get_emails(); // Get all WC_emails objects instances
        $customer_email = $order->get_billing_email(); // The customer email
    }

    if ( $new_status == 'cancelled' ) {
        // change the recipient of this instance
        $wc_emails['WC_Email_Cancelled_Order']->recipient = $customer_email;
        // Sending the email from this instance
        $wc_emails['WC_Email_Cancelled_Order']->trigger( $order_id );
    } 
    elseif ( $new_status == 'failed' ) {
        // change the recipient of this instance
        $wc_emails['WC_Email_Failed_Order']->recipient = $customer_email;
        // Sending the email from this instance
        $wc_emails['WC_Email_Failed_Order']->trigger( $order_id );
    } 
}

将代码放在您的活动子主题(或主题)的function.php文件中,也可以放在任何插件文件中。

这应该适用于WooCommerce 3+。

如果需要,您可以将其添加到现有收件人而不是更改电子邮件:

// Add a recipient in this instance
$wc_emails['WC_Email_Failed_Order']->recipient .= ',' . $customer_email;
相关回答:当订单状态从待处理变为取消时发送电子邮件通知

4
好的,谢谢!你真的救了我的一天,我已经花了太长时间在这个问题上了。祝您有美好的一天先生! - KevDev
很好的解决方案,有没有办法更改电子邮件的内容文本?我希望管理员通知文本与客户通知文本不同。gettext是否是答案? - fightstarr20
祝福这个操作,对于那些想要自定义电子邮件的人,我认为他们应该在这里查看:https://www.skyverge.com/blog/how-to-add-a-custom-woocommerce-email/。 只需在那些插件中禁用触发器即可。 然后,您可以使用此函数来触发: $wc_emails['WC_Expedited_Order_Email']->trigger( $order_id ); - Anthony Kal
您可以在WooCommerce电子邮件中自定义电子邮件模板。 - Anthony Kal
太好了。仍然可以在WooCommerce 6.4.1中使用。 - Marco
对我来说,这段代码在批量取消订单时会出现问题。如果你有两个订单 A 和 B,它们的集体取消将导致人员 A 和管理员收到有关取消订单 A 的电子邮件,而人员 B 收到有关取消订单 A 和 B 的电子邮件。因此,人员 B 得到了与他们无关的订单信息。 - omicito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接