I am trying to get this function to work consistently but am facing issues. I have a WooCommerce site that allows users to order products without paying immediately. Instead, they have 8 hours to pay cash to any in-store partner, who will then mark the order as complete (changing the order status from on-hold to completed). If they don’t make the payment within 8 hours, their order should automatically cancel (changing the order status from on-hold to cancelled).
The problem is that this function works intermittently. I added the function using the Code Snippets plugin. Additionally, I am using Memcached and Redis, hosted on cloudways; which I mention in case they are causing the issue. I am a beginner at this.
// Hook into WooCommerce order status change to on-hold
add_action('woocommerce_order_status_on-hold', 'schedule_cancel_on_hold_order_event');
function schedule_cancel_on_hold_order_event($order_id) {
// Schedule the event to run 2 minutes later (for testing purposes)
if ( ! wp_next_scheduled( 'cancel_on_hold_order_event', array( 'order_id' => $order_id ) ) ) {
wp_schedule_single_event(time() + 2 * MINUTE_IN_SECONDS, 'cancel_on_hold_order_event', array('order_id' => $order_id));
error_log("Scheduled cancel_on_hold_order_event for order ID: $order_id");
}
}
// Hook into our custom event
add_action('cancel_on_hold_order_event', 'cancel_on_hold_order');
function cancel_on_hold_order($order_id) {
// Get the order
$order = wc_get_order($order_id);
// Check if the order is still on-hold
if ($order && $order->get_status() == 'on-hold') {
// Cancel the order
$order->update_status('cancelled', __('Order cancelled automatically after 2 minutes on-hold', 'your-text-domain'));
error_log("Order ID $order_id cancelled automatically.");
} else {
error_log("Order ID $order_id was not on-hold or does not exist.");
}
}
// Clear scheduled event on order status change to something other than on-hold
add_action('woocommerce_order_status_changed', 'clear_cancel_on_hold_order_event', 10, 4);
function clear_cancel_on_hold_order_event($order_id, $old_status, $new_status, $order) {
if ($old_status === 'on-hold' && $new_status !== 'on-hold') {
wp_clear_scheduled_hook('cancel_on_hold_order_event', array('order_id' => $order_id));
error_log("Cleared scheduled event for order ID: $order_id");
}
}
i ofloaded cron to server by disabling wp cron and adding cron server side
define('DISABLE_WP_CRON', true);
*/5 * * * * wget -q -O – https://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
I am expecting all orders whose order status is not changed to completed be automatically cancelled in 2 minutes(for testing purposes). Some times orders get cancelled as expected, sometimes not
Pink is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.