The customer requested me to disable email notification for free products in WoocCmmerce, but only in case the order contains this free product id = 5274
If the order includes this free product and any other product, the order email notification should be trigger.
This is the code I use now:
add_filter('woocommerce_email_recipient_new_order', 'disable_notification_free_product', 10, 2);
function disable_notification_free_product($recipient, $order)
{
$page = $_GET['page'] = isset($_GET['page']) ? $_GET['page'] : '';
if ('wc-settings' === $page) {
return $recipient;
}
if (!$order instanceof WC_Order) {
return $recipient;
}
//the product id is 5274
$items = $order->get_items();
$items_cart = WC()->cart->get_cart_contents_count();
foreach ($items as $item) {
$product_id = $item['product_id'];
if ($product_id == 5274 and $items_cart == 1) {
$recipient = '';
}
return $recipient;
}
}
The code works before adding "and $items_cart == 1" to disable the email notification when the free product is in the order, but after adding the "and $items_cart == 1" nothing changed. Any advice?
That's because WC()->cart->get_cart_contents_count()
should only be used with the $cart
object, with the $order
object you can use count( $order->get_items() )
So you get:
function filter_woocommerce_email_recipient_new_order( $recipient, $order, $email ) {
// Avoiding backend displayed error in WooCommerce email settings
if ( ! is_a( $order, 'WC_Order' ) ) return $recipient;
// Loop through order items
foreach ( $order->get_items() as $key => $item ) {
// Product ID
$product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
// Product ID occurs and count is equal to 1
if ( in_array( $product_id, array( 5274 ) ) && count( $order->get_items() ) == 1 ) {
$recipient = '';
break;
}
}
return $recipient;
}
add_filter( 'woocommerce_email_recipient_new_order', 'filter_woocommerce_email_recipient_new_order', 10, 3 );