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 [email protected]. When Product B is sold, the email will be sent to [email protected]. When Product C is sold, the email will be sent to [email protected] so forth.
Is there some code I can add to functions.php to achieve this?
Based on "https://stackoverflow.com/questions/54034812/different-recipients-based-on-product-category-in-woocommerce-email-notification/54038420#54038420" 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(
'[email protected]' => array(37),
'[email protected]' => array(40),
'[email protected]' => array(53, 57),
);
// Loop through order items
foreach ( $order->get_items() as $item ) {
$product_id = $item->get_product_id();
$variation_id = $item->get_variation_id();
// Loop through defined product categories
foreach ( $recipients_product_ids as $email => $product_ids ) {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With