Kapil Goyal
Kapil Goyal

Reputation: 117

Add recipients from product custom fields to Woocommerce new order email notification

In Woocommerce, I would like to add a email custom field with the Advanced Custom Fields plugin to products post type.

If customer place an order I would like to add the corresponding email adresses for each order items to new order email notification .

How to add recipients from product custom fields to Woocommerce new order email notification?

Upvotes: 1

Views: 1074

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253773

For "New order" email notification, here is the way to add custom emails from items in the order (The email custom field is set with ACF in the products).

So you will set first a custom field in ACF for "product" post type:

enter image description here

Then you will have in backend product edit pages:

enter image description here

Once done and when that product custom-fields will be all set with an email adress, you will use this code that will add to "New order" notification the emails for each corresponding item in the order:

add_filter( 'woocommerce_email_recipient_new_order', 'add_item_email_to_recipient', 10, 2 );
function add_item_email_to_recipient( $recipient, $order ) {
    if( is_admin() ) return $recipient;

    $emails = array();

    // Loop though  Order IDs
    foreach( $order->get_items() as $item_id => $item ){
        // Get the student email
        $email = get_field( 'product_email', $item->get_product_id() );
        if( ! empty($email) )
            $emails[] = $email; // Add email to the array
    }

    // If any student email exist we add it
    if( count($emails) > 0 ){
        // Remove duplicates (if there is any)
        $emails = array_unique($emails);
        // Add the emails to existing recipients
        $recipient .= ',' . implode( ',', $emails );
    }
    return $recipient;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Related: Send Woocommerce Order to email address listed on product page

Upvotes: 4

Related Questions