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 ?
CodePudding user response:
It looks like "woocommerce_cancel_unpaid_submitted" action doesn't exists. You can use "woocommerce_cancel_unpaid_orders" action.
CodePudding user response:
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);
}
}