Search code examples
phpwordpresswoocommerceordersemail-notifications

Woocommerce email notification recipient conditionally based on custom field


I have a checkout form with a custom field.

I would like to add an extra recipient to an order email based on the value in the custom field. The custom field is currently a drop down menu with only 3 options.

Below is the code I was able to piece together with some googling however this does not appear to work.

function sv_conditional_email_recipient( $recipient, $order ) {

    $custom_field = get_post_meta($orderid, 'custom_field', true);

    if ($custom_field == "Value 1") 
    {
        $recipient .= ', [email protected]';
    } 
    elseif ($custom_field == "Value 2") 
    {
        $recipient .= ', [email protected]';
    }
    elseif ($custom_field == "Value 3") 
    {
        $recipient .= ', [email protected]';
    }
    return $recipient;
}

add_filter( 'woocommerce_email_recipient_new_order', 'sv_conditional_email_recipient', 10, 2 );

Any help is appreciated.

Thanks.


Solution

  • Your problem comes from the $orderid that is not defined. Try this instead:

    add_filter( 'woocommerce_email_recipient_new_order', 'new_order_conditional_email_recipient', 10, 2 );
    function new_order_conditional_email_recipient( $recipient, $order ) {
        if ( ! is_a( $order, 'WC_Order' ) ) return $recipient; // (Optional)
    
        // Get the order ID (retro compatible)
        $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
    
        // Get the custom field value (with the right $order_id)
        $custom_field = get_post_meta( $order_id, 'custom_field', true );
    
        if ($custom_field == "Value 1") 
            $recipient .= ', [email protected]'; 
        elseif ($custom_field == "Value 2") 
            $recipient .= ', [email protected]';
        elseif ($custom_field == "Value 3") 
            $recipient .= ', [email protected]';
    
        return $recipient;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Code is tested and works on WooCommerce 2.6.x and 3+.

    This hook is targeting "new_order" email notification only