Advertisement
vapvarun

Prevent Duplicate Orders in WooCommerce within One Hour. 2

Jan 10th, 2024
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. /**
  2. * Prevent Duplicate Orders in WooCommerce within One Hour.
  3. * Checks if the current user has placed an order with the same products or total amount in the last hour.
  4. */
  5. add_action( 'woocommerce_checkout_process', 'wbcom_prevent_duplicate_order_within_one_hour' );
  6.  
  7. function wbcom_prevent_duplicate_order_within_one_hour() {
  8. $current_user = wp_get_current_user();
  9. $current_cart_items = WC()->cart->get_cart();
  10. $current_cart_total = WC()->cart->total;
  11.  
  12. $args = array(
  13. 'customer_id' => $current_user->ID,
  14. 'date_created' => '>' . ( time() - HOUR_IN_SECONDS ),
  15. 'status' => array( 'on-hold', 'processing', 'completed' ),
  16. 'limit' => -1 // Retrieve all orders in the timeframe
  17. );
  18.  
  19. $orders = wc_get_orders( $args );
  20.  
  21. foreach ( $orders as $order ) {
  22. $order_items = $order->get_items();
  23. $order_total = $order->get_total();
  24.  
  25. // Check if order total is the same
  26. if ( $current_cart_total == $order_total ) {
  27. wc_add_notice( 'An order with the same total amount has been placed in the last hour. Please wait before placing a new order.', 'error' );
  28. return;
  29. }
  30.  
  31. // Check if cart contains the same products
  32. if ( wbcom_check_same_products( $current_cart_items, $order_items ) ) {
  33. wc_add_notice( 'An order with the same products has been placed in the last hour. Please wait before placing a new order.', 'error' );
  34. return;
  35. }
  36. }
  37. }
  38.  
  39. function wbcom_check_same_products( $current_cart_items, $order_items ) {
  40. $cart_product_ids = array_keys( wp_list_pluck( $current_cart_items, 'product_id' ) );
  41. $order_product_ids = array_keys( wp_list_pluck( $order_items, 'product_id' ) );
  42.  
  43. sort( $cart_product_ids );
  44. sort( $order_product_ids );
  45.  
  46. return $cart_product_ids === $order_product_ids;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement