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!
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 CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
add_action( 'woocommerce_order_status_pending', 'bbloomer_cancel_failed_pending_order_event' );
function bbloomer_cancel_failed_pending_order_event( $order_id ) {
if ( ! wp_next_scheduled( 'bbloomer_cancel_failed_pending_order_after_one_hour', array( $order_id ) ) ) {
wp_schedule_single_event( time() + 3600, 'bbloomer_cancel_failed_pending_order_after_one_hour', array( $order_id ) );
}
}
add_action( 'bbloomer_cancel_failed_pending_order_after_one_hour', 'bbloomer_cancel_order' );
function bbloomer_cancel_order( $order_id ) {
$order = wc_get_order( $order_id );
wp_clear_scheduled_hook( 'bbloomer_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' );
}
}
Hello Rodolfo! Great blog, you helped me alot already :). One quick question – can I change
to
to apply the same code to processing orders?
Of course