问题
I’m looking to sell a number of virtual items on WooCommerce for different businesses. So when the customer has checked out, I'd like the email to be sent to the relevant business (not to admin).
So when Product A is sold, an email will go to a@email.com. When Product B is sold, the email will be sent to b@email.com. When Product C is sold, the email will be sent to c@email.com...and so forth.
Is there some code I can add to functions.php to achieve this?
回答1:
Based on "Different recipients based on product category in WooCommerce email notification" answer code, the following will allow a add a different email recipient based on the product Id:
add_filter( 'woocommerce_email_recipient_new_order', 'custom_email_recipient_new_order', 10, 2 );
function custom_email_recipient_new_order( $recipient, $order ) {
// Not in backend when using $order (avoiding an error)
if( ! is_a($order, 'WC_Order') ) return $recipient;
// Define the email recipients / product Ids pairs
$recipients_product_ids = array(
'product.one@email.com' => array(37),
'product.two@email.com' => array(40),
'product.three@email.com' => array(53, 57),
);
// Loop through order items
foreach ( $order->get_items() as $item ) {
// Loop through defined product categories
foreach ( $recipients_product_ids as $email => $product_ids ) {
$product_id = $item->get_product_id();
$variation_id = $item->get_variation_id();
if( array_intersect([$product_id, $variation_id], $product_ids) && strpos($recipient, $email) === false ) {
$recipient .= ',' . $email;
}
}
}
return $recipient;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
来源:https://stackoverflow.com/questions/55546448/different-recipients-based-on-products-sold-in-woocommerce-email-notification