Change order status when order has backorder items in it

 ̄綄美尐妖づ 提交于 2020-03-20 12:48:20

问题


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.


回答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




回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/42577974/change-order-status-when-order-has-backorder-items-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!