Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

php - Auto completed status for all existing processing orders in WooCommerce

I am using on WooCommerce this little peace of code from this answer to autocomplete paid processing orders:

/**
 * AUTO COMPLETE PAID ORDERS IN WOOCOMMERCE
 */
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_paid_order', 10, 1 );
function custom_woocommerce_auto_complete_paid_order( $order_id ) {
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );

  // No updated status for orders delivered with Bank wire, Cash on delivery and Cheque payment methods.
  if ( ( get_post_meta($order->id, '_payment_method', true) == 'bacs' ) || ( get_post_meta($order->id, '_payment_method', true) == 'cod' ) || ( get_post_meta($order->id, '_payment_method', true) == 'cheque' ) ) {
    return;
    } 
  // "completed" updated status for paid Orders with all others payment methods
    else {
        $order->update_status( 'completed' );
    }
} 

But the problem is that I use a special payment gateway by SMS which API is bridged on 'cod' payment method, and the orders stay sometimes in on-hold status on this 'woocommerce_thankyou' hook.

So I will need to scan all the time the 'processing' orders to pass them in complete status. I have tried different things and hooks, but I cant get it work as expected.

How can I do this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get this working you just need a little function that will scan all orders with a "processing" status on the 'init' hook, and that will update this status to "completed".

Here is that code:

function auto_update_orders_status_from_processing_to_completed(){
    // Get all current "processing" customer orders
    $processing_orders = wc_get_orders( $args = array(
        'numberposts' => -1,
        'post_status' => 'wc-processing',
    ) );
    if(!empty($processing_orders))
        foreach($processing_orders as $order)
            $order->update_status( 'completed' );
}
add_action( 'init', 'auto_update_orders_status_from_processing_to_completed' );

This code is tested and works.

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

ADVICE & UPDATE

There is a little bug around email notifications sent twice that is solved in here:
Avoid repetitive emails notification on some auto completed orders


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...