Search code examples
phpwordpresswoocommerceemail-notifications

Send WooCommerce email notifications to billing and user email address


I wanted to use woocommerce_mail_headers filter to send custom emails to billing email address and user email address.

I read a lot of different posts about this issue on the last days but i was not able to find a working solution.

The following code is ok when $cc_email and $user_name are predefined but not when they are variable (depending on $order).

my_custom_email is the id of my email template (very close to WooCommerce email ones)

add_filter( 'woocommerce_email_headers', 'cc_user_function', 10, 3);
 
function cc_user_function($headers, $email_id, $order) {
       
    if ($email_id == 'my_custom_email'){
         $order_nr = wc_get_order( $order );
         $user_id   = $order_nr->get_user_id();
        $cc_email = get_userdata($user_id)->user_email ;
      
           $user_name  = $user->get_first_name().' ';
           $user_name .= $user->get_last_name();

    $formatted_email = utf8_decode($user_name . ' <' . $cc_email . '>');

    $headers .= 'Cc: '.$formatted_email .'\r\n';
}

            return $headers;
}

Can you help me to solve this problem?


Solution

  • To get an instance of the WP_User object you can use $order->get_user()

    So you get:

    function filter_woocommerce_email_headers( $header, $email_id, $order ) {
        // For a given email id & user id exists (no guests)
        if ( $email_id == 'customer_on_hold_order' && $order->get_user_id() > 0 ) {
            // Get an instance of the WP_User object
            $user = $order->get_user();
            
            // Get user email
            $user_email = $user->user_email;
            
            // Get first & last name
            $user_name = $user->first_name . ' ';
            $user_name .= $user->last_name;
        
            // Prepare the the data
            $formatted_email = utf8_decode( $user_name . ' <' . $user_email . '>' );
    
            // Add Cc to headers
            $header .= 'Cc: ' . $formatted_email . '\r\n';
        }
    
        return $header;
    }
    add_filter( 'woocommerce_email_headers', 'filter_woocommerce_email_headers', 10, 3 );