Search code examples
wordpresswoocommerceproductordersemail-notifications

Display message in WooCommerce email notifications when order has backorder items in it


I am trying to display a specific message on the Order confirmation email IF one of several products of your order is/are on backorder.

I am struggling to get the right function to scan all the products and get my boolean working.

My current code:

add_action( 'woocommerce_email_after_order_table', 'backordered_items_checkout_notice_email', 20, 4 );
function backordered_items_checkout_notice_email( $order, $sent_to_admin, $plain_text, $email ) {
  $found2 = false;
  foreach ( $order->get_items() as $item ) {
            if( $item['data']->is_on_backorder( $item['quantity'] ) ) {
            $found2 = true;
            break;
        }
    }

    if( $found2 ) {
        if ( $email->id == 'customer_processing_order' ) {echo ' <strong>'.__('⌛ One or several products are Currently out of stock. <br/>Please allow 2-3 weeks for delivery.', 'plugin-mve').'</strong><br/>';}
    
    }
}

With this code, when you click on "Order" the page just freezes and no email is sent. But I get the order in the backend.

Could anyone give me a hand to fix?


Solution

  • Your code contains a CRITICAL uncaught error, namely: Call to a member function is_on_backorder() on null

    Following code will add the message for the customer_processing_order email notification. Also see: How to target other WooCommerce order emails

    So you get:

    function action_woocommerce_email_after_order_table( $order, $sent_to_admin, $plain_text, $email ) {
        // Initialize
        $flag = false;
        
        // Target certain email notification
        if ( $email->id == 'customer_processing_order' ) {
            // Iterating through each item in the order
            foreach ( $order->get_items() as $item ) {
                // Get a an instance of product object related to the order item
                $product = $item->get_product();
    
                // Check if the product is on backorder
                if ( $product->is_on_backorder() ) {
                    $flag = true;
                    
                    // Stop the loop
                    break;
                }
            }
            
            // True
            if ( $flag ) {
                echo '<p style="color: red; font-size: 30px;">' . __( 'My message', 'woocommerce' ) . '</p>';
            }
        }
    }
    add_action( 'woocommerce_email_after_order_table', 'action_woocommerce_email_after_order_table', 10, 4 );