
In a recent Business Bloomer Club discussion, a WooCommerce store owner wanted to simulate the automatic cancellation of “Pending Payment” orders after a set time.
WooCommerce has a built-in feature to move pending payments to “Canceled” status, but in this case, the auto-cancellation wasn’t consistently triggering during testing with Mollie’s test API key. Since no actual order is created on Mollie’s platform with the test key, pending orders in the shop would remain in that status, causing issues with testing sub-orders in the Yith Deposit plugin.
For anyone facing similar challenges, here’s a potential solution using WooCommerce’s Action Scheduler.
Solution: Using Action Scheduler to Automate Order Status Change
To automatically cancel pending orders after a specified time, you can use the Action Scheduler to check the status of each order after a set interval. If the order is still pending, it will be canceled; if not, no action will be taken.
Step-by-Step Solution
- Add a Custom Action: Create an action to check the order status at a given interval.
- Schedule the Event: Set up a schedule to trigger this action for each new order.
- Check & Update Status: When the event runs, check if the order status is still “Pending Payment.” If so, update it to “Canceled.”
Here’s some sample code to illustrate the approach:
// Hook into WooCommerce order creation
add_action( 'woocommerce_checkout_order_processed', 'schedule_pending_order_cancellation', 10, 1 );
function schedule_pending_order_cancellation( $order_id ) {
// Schedule the event to check order status after 24 hours (or any desired time)
if ( ! as_has_scheduled_action( 'check_and_cancel_pending_order', array( $order_id ) ) ) {
as_schedule_single_action( time() + DAY_IN_SECONDS, 'check_and_cancel_pending_order', array( $order_id ) );
}
}
// Define the callback for the scheduled action
add_action( 'check_and_cancel_pending_order', 'cancel_pending_order_if_needed' );
function cancel_pending_order_if_needed( $order_id ) {
$order = wc_get_order( $order_id );
// If the order is still in "Pending Payment" status, change it to "Canceled"
if ( $order && $order->has_status( 'pending' ) ) {
$order->update_status( 'cancelled', __( 'Order canceled automatically due to pending status.', 'woocommerce' ) );
}
}
Explanation
- Event Scheduling: When a new order is created, the function
schedule_pending_order_cancellation
schedules a single action using WooCommerce’s Action Scheduler, set to run after 24 hours. - Order Status Check: The
cancel_pending_order_if_needed
function checks if the order is still pending. If yes, it updates the status to “Canceled.”
This setup provides a reliable way to simulate automatic cancellation for testing purposes, even without real-time responses from payment gateways.