Automatically cancel a WooCommerce order after 3 failed attempts

In WooCommerce, when a payment fails, the order status changes to “failed“. This can happen for several reasons: a declined card, insufficient funds, or a payment gateway error. If your store handles a high volume of orders, too many failed orders can clutter your system and cause confusion.

A helpful solution is to automatically cancel any order that has failed 3 times, keeping your store clean and organized.

In this article, I’ll show you a PHP snippet you can paste into your child theme’s functions.phpfile or add to a custom plugin.

 

How does the logic work?

  1. Every time an order status changes to “failed”, we’ll count how many times that order has already failed.
  2. We’ll store that number in a custom order meta field.
  3. If the counter reaches 3, we automatically change the order status to “cancelled”.

 

PHP code to cancel orders after 3 failures

<?php
add_action( 'woocommerce_order_status_failed', 'autoCancelFailedOrder' );

function autoCancelFailedOrder( $orderId ) {
    $order = wc_get_order( $orderId );

    if ( ! $order ) {
        return;
    }

    // Get current fail count
    $failCount = $order->get_meta( '_fail_count' );

    if ( ! $failCount ) {
        $failCount = 1;
    } else {
        $failCount++;
    }

    // Save the new fail count
    $order->update_meta_data( '_fail_count', $failCount );
    $order->save();

    // Cancel the order if it failed 3 times
    if ( $failCount >= 3 ) {
        $order->update_status( 'cancelled', 'Order automatically cancelled after 3 failed attempts.' );
    }
}

 

Where should you place this code?

You have two options:

  1. In your child theme’s functions.php file – ideal if you don’t have a custom plugin.
  2. Inside a custom plugin – recommended if you want to keep your code separate from the theme.

 

Can you customize this behavior?

Of course! Some ideas:

  • Instead of canceling the order, you could send an email notification to the store admin.
  • You could reduce the number of attempts (e.g., cancel after 2 failures).
  • You could change the order status to something custom like pending-verification.

 

This small snippet helps you keep your WooCommerce store tidy by avoiding the buildup of failed orders. Plus, it automates a task you’d otherwise have to do manually.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x