问题
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