WooCommerce:订单移入回收站时触发邮件通知的钩子及代码适配
WooCommerce订单移入回收站触发邮件的钩子及代码修改
核心钩子说明
WooCommerce的订单本质是WordPress自定义文章类型shop_order,当订单被移入回收站时,会触发WordPress通用的文章回收站钩子:wp_trash_post。这个钩子会在任何文章(包括订单)被移入回收站时执行,我们只需在钩子回调中判断当前操作的是订单即可。
完整修改代码
在你现有代码的基础上,添加对wp_trash_post钩子的监听,就能实现订单移入回收站时的邮件发送功能。以下是修改后的完整代码:
// 处理订单取消/失败状态的邮件 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(); // 获取所有WC邮件实例 $customer_email = $order->get_billing_email(); // 获取客户邮箱 } if ( $new_status == 'cancelled' ) { $wc_emails['WC_Email_Cancelled_Order']->recipient = $customer_email; $wc_emails['WC_Email_Cancelled_Order']->trigger( $order_id ); } elseif ( $new_status == 'failed' ) { $wc_emails['WC_Email_Failed_Order']->recipient = $customer_email; $wc_emails['WC_Email_Failed_Order']->trigger( $order_id ); } } // 处理订单移入回收站的邮件 add_action('wp_trash_post', 'send_trash_order_email_notification', 10, 1); function send_trash_order_email_notification( $post_id ) { // 过滤非订单类型的回收站操作 if ( get_post_type( $post_id ) !== 'shop_order' ) { return; } $order = wc_get_order( $post_id ); if ( !$order ) { return; } $wc_emails = WC()->mailer()->get_emails(); $customer_email = $order->get_billing_email(); // 示例:复用取消订单的邮件模板发送 $wc_emails['WC_Email_Cancelled_Order']->recipient = $customer_email; $wc_emails['WC_Email_Cancelled_Order']->trigger( $post_id ); // 若需要完全自定义邮件内容,可替换为以下代码: // $mailer = WC()->mailer(); // $subject = '您的订单已被移入回收站'; // $message = "尊敬的客户,您的订单 #{$order->get_order_number()} 已被移入回收站,如有疑问请联系我们。"; // $mailer->send( $customer_email, $subject, $message ); }
关键注意点
- 必须通过
get_post_type($post_id)判断是否为shop_order,避免wp_trash_post钩子触发其他文章类型的误操作。 - 如果默认的取消订单邮件模板不符合回收站场景的需求,直接使用代码中注释的自定义邮件发送逻辑即可。
- 代码建议添加到主题的
functions.php文件或独立的自定义插件中,防止主题更新导致代码丢失。
内容的提问来源于stack exchange,提问作者Edu Rafael
相关产品推荐
相关产品推荐

