Send new order email to CC if order has items from a certain category in WooCommerce

305 views Asked by At

I want to send admin new order e-mail to cc, if order has items from a parent product category:

I am using the code below but this doesn't seem to work. The mail is being sent but I receive a notification for an undefined variable. The person in CC does not receive the message either

add_filter( 'woocommerce_email_headers', 'bbloomer_order_completed_email_add_cc_bcc', 9999, 3 );
 
function bbloomer_order_completed_email_add_cc_bcc( $headers, $email_id, $order ) {
    
      $order = wc_get_order( $order_id ); // The WC_Order object
    if ( 'new_order' == $email_id && $orderid['product_cat']== 69) {
        $headers .= "Cc: Name <[email protected]>" . "\r\n"; // del if not needed
    
    }
    return $headers;
}

Someone who wants to take a closer look at this?

1

There are 1 answers

0
7uc1f3r On BEST ANSWER
  • The use of wc_get_order() is not necessary, you can already access the $order object via the parameters
  • $orderid['product_cat'] does not exist
  • Explanation via comments added in the code

So you could use

function filter_woocommerce_email_headers( $header, $email_id, $order ) {
    // New order
    if ( $email_id == 'new_order' ) {       
        // Set categories
        $categories = array( 'categorie-1', 'categorie-2' );
        
        // Flag = false by default
        $flag = false;
        
         // Loop trough items
        foreach ($order->get_items() as $item ) {
            // Product id
            $product_id = $item['product_id'];

            // Has term (a certain category in this case)
            if ( has_term( $categories, 'product_cat', $product_id ) ) {
                // Found, flag = true, break loop
                $flag = true;
                break;
            }
        }
        
        // True
        if ( $flag ) {  
            // Prepare the the data
            $formatted_email = utf8_decode('My test <[email protected]>');

            // Add Cc to headers
            $header .= 'Cc: ' . $formatted_email . '\r\n';
        }
    }

    return $header;
}
add_filter( 'woocommerce_email_headers', 'filter_woocommerce_email_headers', 10, 3 );