Search code examples
phpwordpresswoocommerceemail-notificationspayment-method

Additional email recipient based on payment method Ids in WooCommerce


I am trying to add additional email recipient based on payment method Id on WooCommerce "New order" email notification.

Here is my code:

function at_conditional_admin_email_recipient($recipient, $order){
 //   if( ! is_a($order, 'WC_Order') ) return $recipient;
   
    if ( get_post_meta($order->id, '_payment_method', true) == 'my_custom_gateway_id' ) {
        $recipient .= ', [email protected]';
    } else {
        $recipient .= ', [email protected]';
    }
    return $recipient;
    
    
};
add_filter( 'woocommerce_email_recipient_new_order', 'at_conditional_admin_email_recipient', 10, 2 );

But the hook doesn't seem firing my function. What could be the reason?


Solution

  • Your code is outdated since Woocommerce 3, try the following instead:

    add_filter( 'woocommerce_email_recipient_new_order', 'payment_id_based_new_order_email_recipient', 10, 2 );
    function payment_id_based_new_order_email_recipient( $recipient, $order ){
        // Avoiding backend displayed error in Woocommerce email settings (mandatory)
        if( ! is_a($order, 'WC_Order') ) 
            return $recipient;
    
        // Here below set in the array the desired payment Ids
        $targeted_payment_ids = array('bacs');
       
        if ( in_array( $order->get_payment_method(), $targeted_payment_ids ) ) {
            $recipient .= ', [email protected]';
        } else {
            $recipient .= ', [email protected]';
        }
        return $recipient;
    }
    

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

    Also sometimes the problem can be related to a wrong payment method Id string in your code (so try first for example with WooCommerce "cod" or "bacs" payment methods ids, to see if the code works).