我正在寻找一种解决方案,当特定客户组(用户角色)的客户完成订单时,我们可以禁用 woocommerce 发送电子邮件通知。
我找到了有关阻止发送特定产品 ID 的电子邮件的情况的答案。 禁用特定产品的 WooCommerce 电子邮件通知。 也许这也可能解决我们的“问题”?
亲切的问候, 基斯
您可以对任何电子邮件使用该钩子,并且在回调函数中您可以检查用户是否具有特定角色
function change_new_order_email_recipient( $recipient, $order ) {
global $woocommerce;
$uid = $order->get_user_id();
$user_meta=get_userdata($uid);
$user_roles=$user_meta->roles;
if(in_array('customer', $user_roles)){ // Prevent email if user role is customer
$recipient ='';
}
return $recipient;
}
add_filter('woocommerce_email_recipient_customer_completed_order', 'change_new_order_email_recipient', 1, 2);
我已经快速检查了代码并且正在工作
许多人建议使用 $recipient = '' 来阻止电子邮件通知,这似乎无意中“破坏”了收件人的电子邮件,但实际上并没有阻止电子邮件的发送。
但是,我找到了一个更优雅的解决方案,可以真正阻止电子邮件发送,而不仅仅是破坏它。此方法的灵感来自于 WooCommerce 文档中描述的有关如何取消/删除 WooCommerce 电子邮件的技术 (https://woocommerce.com/document/unhookremove-woocommerce-emails/):
`// Completed order emails
remove_action( 'woocommerce_order_status_completed_notification', array( $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ) );`
基于此,我开发了一个可以有效阻止电子邮件发送的版本。我相信这种方法更加优雅。请告诉我你的想法。
add_action( 'woocommerce_email', 'customize_woocommerce_emails' );
function customize_woocommerce_emails( $email_class ) {
// Check if the WC_Email_Customer_Completed_Order is enabled and set to send emails
if ( isset( $email_class->emails['WC_Email_Customer_Completed_Order'] ) ) {
// Hook into the order status completed action to check for the specific product
add_action( 'woocommerce_order_status_completed_notification', function( $order_id ) use ( $email_class ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
// Define the specific product ID you want to check for
$specific_product_id = YOUR_SPECIFIC_PRODUCT_ID; // Replace this with your actual product ID
foreach ( $order->get_items() as $item ) {
if ( $item->get_product_id() == $specific_product_id ) {
// If the specific product is found, remove the action that triggers the email
remove_action( 'woocommerce_order_status_completed_notification', [ $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ] );
break;
}
}
}, 9 ); // Priority set to 9 to ensure it runs before the default email action
}
}