简体   繁体   中英

Auto change Woocommerce order status Failed -> Canceled

I am trying to automatically change Woocommerce orders with "Failed" status to "Cancel" status after 24h. It means the customer has not been able to pay his order.

I have tried many things so far but was not able to make it work. Here is the mu-plugin I have created :

    <?php
add_action( 'woocommerce_cancel_unpaid_submitted', 'cancel_failed_orders' );
function cancel_failed_orders() {
    $days_delay = 1; 
    $one_day    = 24 * 60 * 60;
    $today      = strtotime( date('Y-m-d') );
    $failed_orders = (array) wc_get_orders( array(
        'limit'        => -1,
        'status'       => 'wc-failed',
        'date_created' => '<' . ( $today - ($days_delay * $one_day) ),
    ) );
    if ( sizeof($failed_orders) > 0 ) {
        $cancelled_text = __("No successful payment", "woocommerce");
        foreach ( $failed_orders as $order ) {
            $order->update_status( 'wc-cancelled', $cancelled_text );
        }
    }
}

Does anyone has any idea what I am missing ?

It looks like "woocommerce_cancel_unpaid_submitted" action doesn't exists. You can use "woocommerce_cancel_unpaid_orders" action.

Here is a solution with wp-cron job. To test it at full install WP Crontrol plugin so you can manualy run the cron job when you need it or wait 1 hour. Your cron job should be listed as name failed_orders_event .

Disable wp-cron and use server cron if you want execution on every hour with or without visitors. There is alot of info on the web.

add_action('failed_orders_event', 'check_failed_orders_every_hour');
// The action will trigger when someone visits your WordPress site
function failed_orders_event_activation() {
    if ( !wp_next_scheduled( 'failed_orders_event' ) ) {
        wp_schedule_event( time(), 'hourly', 'failed_orders_event');
    }
}
add_action('wp', 'failed_orders_event_activation');

function check_failed_orders_every_hour() {
    $failed_orders = wc_get_orders( array(
        'limit'        => -1,
        'status'       => 'failed',
    ));

    foreach ( $failed_orders as $order ) {
        $cancelled_text = __("No successful payment", "woocommerce");
        $order->update_status( 'cancelled',$cancelled_text);
    }
    
}

i need the same but backwards

WooCommerce "Cancelled" Orders change to "failed" status

WooCommerce cancels an abandoned order 24 hours after not receiving payment, the order ON HOLD status automatically goes to CANCELED, so far so good, now when the order changes CANCELLED, I need them to change to "failed" 1 hour later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM