I use this code to auto cancel woocommerce orders, if new orders do not change status before 24 hours. However it does not work, after 24 hours of testing new orders are not auto cancel. Looking forward to receiving help from experts. Thanks
// Create WP-Cron event to run every hour
function schedule_autocancel_wc_orders() {
if ( ! wp_next_scheduled( 'autocancel_wc_orders_hook' ) ) {
wp_schedule_event( time(), 'hourly', 'autocancel_wc_orders_hook' );
}
}
add_action( 'wp', 'schedule_autocancel_wc_orders' );
// Delete WP-Cron schedule when plugin is disabled
function unschedule_autocancel_wc_orders() {
wp_clear_scheduled_hook( 'autocancel_wc_orders_hook' );
}
register_deactivation_hook( __FILE__, 'unschedule_autocancel_wc_orders' );
// Function to automatically cancel orders
function autocancel_wc_orders() {
$args = array(
'limit' => -1, // Lấy tất cả đơn đủ điều kiện
'orderby' => 'date',
'order' => 'ASC',
'status' => array( 'wc-pending', 'wc-ywraq-new', 'wc-ywraq-pending' ),
'date_created' => '<' . ( time() - DAY_IN_SECONDS ) // Chỉ lấy đơn hơn 24h
);
$orders = wc_get_orders( $args );
foreach ( $orders as $order ) {
$order->update_status( 'cancelled', 'Cancelled for missing payment' );
}
}
add_action( 'autocancel_wc_orders_hook', 'autocancel_wc_orders' );