Different recipients based on products sold in WooCommerce email notification
Asked Answered
O

1

4

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?

Oration answered 6/4, 2019 at 6:22 Comment(0)
C
4

Based on "https://mcmap.net/q/1703064/-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.

Cuculiform answered 6/4, 2019 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.