Woocommerce email notification recipient conditionally based on custom field

有些话、适合烂在心里 提交于 2019-12-21 23:30:03

问题


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 .= ', email1@gmail.com';
    } 
    elseif ($custom_field == "Value 2") 
    {
        $recipient .= ', email2@gmail.com';
    }
    elseif ($custom_field == "Value 3") 
    {
        $recipient .= ', email3@gmail.com';
    }
    return $recipient;
}

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

Any help is appreciated.

Thanks.


回答1:


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 .= ', email1@gmail.com'; 
    elseif ($custom_field == "Value 2") 
        $recipient .= ', email2@gmail.com';
    elseif ($custom_field == "Value 3") 
        $recipient .= ', email3@gmail.com';

    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




来源:https://stackoverflow.com/questions/45124313/woocommerce-email-notification-recipient-conditionally-based-on-custom-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!