Home » WooCommerce: Automatically Cancel Orders

WooCommerce: Automatically Cancel Orders

by Tutor Aspire

You may wondering – “but I can already do that from the WooCommerce settings!“. Yes, that’s correct; go to WooCommerce Settings > Products > Inventory and set the “Hold Stock Minutes” value. After that period, unpaid orders will be marked as cancelled to make sure the stock goes back to the initial value.

The problem is – what if you don’t want to use the “Hold Stock Minutes” thing, and even better, what if you don’t use stock management at all? In that case, orders won’t be marked as cancelled automatically.

Also, what if you need to do conditional work e.g. you only want to cancel “failed” orders, while you want to keep “pending” ones as they are? Even in this case, the “hold stock” option won’t work, as you need to specify which order status you want to target and then run the cancel function.

Either way, enjoy!

Let’s schedule an event that automatically cancels WooCommerce unpaid orders of a certain order status e.g. Failed Orders.

PHP Snippet: Programmatically Cancel Orders After 1 Hour

Please note, I’ve used the “woocommerce_order_status_{status}” hook, which means you can target any order status you wish (in my case, “woocommerce_order_status_pending” in order to automatically cancel Pending Payment orders after 1 hour).

If you need to edit the time period, simply change “3600” (one hour in seconds) to whatever you like.

 * @snippet       Automatically Cancel Pending Orders After 1h
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 7
 * @donate $9     https://www.tutoraspire.com

add_action( 'woocommerce_order_status_pending', 'tutoraspire_cancel_failed_pending_order_event' );
function tutoraspire_cancel_failed_pending_order_event( $order_id ) {
if ( ! wp_next_scheduled( 'tutoraspire_cancel_failed_pending_order_after_one_hour', array( $order_id ) ) ) {
wp_schedule_single_event( time() + 3600, 'tutoraspire_cancel_failed_pending_order_after_one_hour', array( $order_id ) );

add_action( 'tutoraspire_cancel_failed_pending_order_after_one_hour', 'tutoraspire_cancel_order' );

function tutoraspire_cancel_order( $order_id ) {
$order = wc_get_order( $order_id );
wp_clear_scheduled_hook( 'tutoraspire_cancel_failed_pending_order_after_one_hour', array( $order_id ) );
if ( $order->has_status( array( 'pending' ) ) ) { 
$order->update_status( 'cancelled', 'Pending order cancelled after 1 hour' );

You may also like