Home > front end >  Disable order received emails for virtual products
Disable order received emails for virtual products

Time:12-19

I am currently using the code below to automatically complete virtual and downloadable products.

add_action('woocommerce_thankyou', 'wpd_autocomplete_virtual_orders', 10, 1 );
function wpd_autocomplete_virtual_orders( $order_id ) {
 

        if( ! $order_id ) return;
     
        // Get order
        $order = wc_get_order( $order_id );
     
        // get order items = each product in the order
        $items = $order->get_items();
     
        // Set variable
        $only_virtual = true;
     
        foreach ( $items as $item ) {
             
            // Get product id
            $product = wc_get_product( $item['product_id'] );
     
            // Is virtual
            $is_virtual = $product->is_virtual();
     
            // Is_downloadable
            $is_downloadable = $product->is_downloadable();
     
            if ( ! $is_virtual && ! $is_downloadable  ) {
     
                $only_virtual = false;
     
            }
     
        }
     
        // true
        if ( $only_virtual ) {
     
            $order->update_status( 'completed' );
     
        }
    }

The issue I am facing is that woocommerce sends out two emails in this scenario to the customer. Order Received Order Completed. I am wondering if there is anyway to stop the order received email from going through to the customer and only have the order completed email sent.

Thank You

CodePudding user response:

To prevent the "Order Received" email from being sent to the customer, you can use the woocommerce_email_enabled_customer_processing_order filter hook to disable the email.

Please try to add the following code inside your if ( $only_virtual )

add_filter( 'woocommerce_email_enabled_customer_processing_order', '__return_false' );

CodePudding user response:

The easiest way to achieve this would be to bypass the WooCommerce update_status function as the email sending is built-in to the function.

Instead just update the order in wp_posts:

Replace: $order->update_status( 'completed' );

With:

wp_update_post(['ID' => $order_id, 'post_status' => 'wc-completed']);

You will then only receive the Order Received email!

  • Related