1

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Tushar Khanna
  • 49
  • 1
  • 10

3 Answers3

6

Here is a custom function hooked in woocommerce_thankyou action hook, that will change the order status if this order has a status "on-hold" and if it has any backorder products in it.

You will have to set in the function the desired new status slug change.

Here is that custom function (code is well commented):

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

    if ( ! $order_id )
        return;

    // HERE below set your new status SLUG for paid back orders  
    $new_status = 'completed';

    // Get a an instance of order object
    $order = wc_get_order( $order_id );

    // ONLY for "on-hold" ORDERS Status
    if ( ! $order->has_status('on-hold') )
        return;

    // 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() ){
            // Change this order status
            $order->update_status($new_status);
            break; // Stop the loop
        }
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The code is tested and works.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
1
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

mujuonly
  • 11,370
  • 5
  • 45
  • 75
  • Thanks Working Perfectly But This line shows an error: wc_add_order_item_meta($item_id, 'Backordered', $qty - max(0, $product->get_total_stock())); – Tushar Khanna Mar 04 '17 at 09:30
  • How to get order details in woocommerce? If order contain sale price then i want to change the order status – Tushar Khanna Mar 04 '17 at 10:06
0

edit code error on // Get a an instance of product object related to the order item

$product = version_compare( WC_VERSION, '3.0', '<' ) ? wc_get_product($item['product_id']) : $item->get_product();