Search code examples
phpwordpresswoocommercestatusorders

Change order status when order has backorder items in it


In WooCommerce, How to change the on-hold order status to something else, if this order has back-ordered items in it?

I have tried to use a custom function hooked in woocommerce_order_status_on-hold action hook without success.

Can anyone help me on this issue?

Thanks.


Solution

  • function mysite_hold($order_id) {
    
        $order = new WC_Order($order_id);
        $items = $order->get_items();
        $backorder = FALSE;
    
        foreach ($items as $item) {
            if ($item['Backordered']) {
                $backorder = TRUE;
                break;
            }
        }
        if($backorder){
            $order->update_status('completed'); //change your status here
        }
    }
    add_action('woocommerce_order_status_on-hold', 'mysite_hold');
    
    //You may need to store your backorder info like below
    
    wc_add_order_item_meta($item_id, 'Backordered', $qty - max(0, $product->get_total_stock()));
    

    Please try this snippet