Set admin email as BCC for WooCommerce cancelled and failed orders

Tags: , , , ,



I am currently using this code to send out notifications on failed and cancelled orders.

function wc_cancelled_order_add_customer_email( $recipient, $order )
{ 
 return $recipient . ',' . $order->billing_email; 
} 
add_filter( 'woocommerce_email_recipient_cancelled_order', 'wc_cancelled_order_add_customer_email', 10, 2 ); 
add_filter( 'woocommerce_email_recipient_failed_order', 'wc_cancelled_order_add_customer_email', 10, 2 );

The problem is that those two admin emails I have set in the system under woocommerce settings are also added to the email recipient together with the customers email. Is it possible to tweak this, so the admin E-mail adresses are on BCC instead, so the customer can’t see their email addresses?

Answer

You need to make some little changes to your hooked function and to add an additional hooked function to handle the admin email as BCC recipient:

add_filter( 'woocommerce_email_recipient_cancelled_order', 'custom_cancelled_and_failed_order_email_recipients', 10, 2 ); 
add_filter( 'woocommerce_email_recipient_failed_order', 'custom_cancelled_and_failed_order_email_recipients', 10, 2 );
function custom_cancelled_and_failed_order_email_recipients( $recipient, $order ) { 
    // Check that the WC_Order object always exist
    if( is_a( $order, 'WC_Order' ) )
        $recipients = $order->get_billing_email(); 

    return $recipients;
} 


add_filter( 'woocommerce_email_headers', 'custom_cancelled_and_failed_order_email_headers', 20, 3 );
function custom_cancelled_and_failed_order_email_headers( $header, $email_id, $order ) {
    // Only for 'cancelled' and 'failed' order notifications
    if( in_array( $email_id, ['cancelled_order', 'failed_order'] ) ) { 
        // Get original admin recipient
        $recipient = WC()->mailer()->get_emails()['WC_Email_Cancelled_Order']->settings['recipient'];
        // Add Admin email As Bcc recipient
        $header .= 'Bcc: ' . $recipient . "rn";
    }
    return $header;
}

Code goes in functions.php file of your active child theme (or active theme). It should work.



Source: stackoverflow