questions

Avoid WooCommerce new order notification for specific product exclusively

Rate this post

I implemented the code to run for isolated product, I mean only if the product is in the order ($product_id == 5274), this code works:

add_filter('woocommerce_email_recipient_new_order', 'remove_free_course_notifications', 10, 2);
function remove_free_course_notifications( $recipient, $order )
{
    $page = $_GET['page'] = isset($_GET['page']) ? $_GET['page'] : '';
    if ('wc-settings' === $page) {
        return $recipient;
    }

    if (!$order instanceof WC_Order) {
        return $recipient;
    }
    //my product id is 5274 
    $items = $order->get_items();
    foreach ($items as $item) {
        $product_id = $item['product_id'];
        if ($product_id == 5274) {
            $recipient = '';
        }
        return $recipient;
    }
}

But if a the order has other items (products) at the same time there is no notification sent to the admin.

Please can you let me know how to change this code to send the admin notification for the rest of items included in the order?

 

✔️Solution:

This code is a bit obsolete. Use the following instead, to stop new order admin notification for an “exclusive” defined product:

add_filter( 'woocommerce_email_recipient_new_order', 'remove_free_course_notifications', 10, 2 );
function remove_free_course_notifications( $recipient, $order )
{
    if ( ! is_a( $order, 'WC_Order' ) ) {
        return $recipient;
    }

    $targeted_product_id = 5274; // Here set your product ID
    $other_found = $product_found = false;

    foreach ( $order->get_items() as $item ) {
        $product_id = $item->get_product_id();
        if ( $item->get_product_id() == $targeted_product_id ) {
            $product_found = true;
        } else {
            $other_found = true;
        }
    }
    
    if ( $product_found && ! $other_found ) {
        return '';
    }

    return $recipient;
}

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

Leave a Reply

Your email address will not be published.

Back to top button