Code function
Bạn copy đoạn code sau đây vào file functions.php
function coderlor_cancel_failed_pending_order_event( $order_id ) { if ( ! wp_next_scheduled( 'coderlor_cancel_failed_pending_order_after_one_hour', array( $order_id ) ) ) { wp_schedule_single_event( time() + 3600, 'coderlor_cancel_failed_pending_order_after_one_hour', array( $order_id ) ); } } add_action( 'coderlor_cancel_failed_pending_order_after_one_hour', 'coderlor_cancel_order' ); function coderlor_cancel_order( $order_id ) { $order = wc_get_order( $order_id ); wp_clear_scheduled_hook( 'coderlor_cancel_failed_pending_order_after_one_hour', array( $order_id ) ); if ( $order->has_status( array( 'pending' ) ) ) { $order->update_status( 'cancelled', 'Tự động huỷ đơn hàng sau 1h nếu không được thanh toán' ); } }
Giải thích code
Khi đơn hàng có trạng thái pending (woocommerce_order_status_pending), hàm coderlor_cancel_failed_pending_order_event sẽ được kích hoạt.
Hàm coderlor_cancel_failed_pending_order_event sẽ kiểm tra xem đã có sự kiện huỷ nào được lên lịch cho đơn hàng chưa. Nếu chưa, nó sẽ tạo một sự kiện trì hoãn (delay) sau 1 giờ bằng wp_schedule_single_event.
Sau đúng 1 giờ, nếu đơn hàng vẫn chưa được thanh toán (tức vẫn ở trạng thái pending), WordPress sẽ gọi hàm coderlor_cancel_order.
Hàm coderlor_cancel_order sẽ:
- Lấy đối tượng đơn hàng qua ID.
- Xoá lịch trình sự kiện đã tạo cho đơn hàng này (tránh lặp lại).
- Nếu đơn hàng vẫn còn trạng thái pending, sẽ cập nhật sang trạng thái cancelled, kèm theo lý do: “Tự động huỷ đơn hàng sau 1h nếu không được thanh toán”.
Chỉ đơn giản thế thôi. Chúc bạn thành công !