/**
* Prevent Duplicate Orders in WooCommerce within One Hour.
* Checks if the current user has placed an order with the same products or total amount in the last hour.
*/
add_action( 'woocommerce_checkout_process', 'wbcom_prevent_duplicate_order_within_one_hour' );
function wbcom_prevent_duplicate_order_within_one_hour() {
$current_user = wp_get_current_user();
$current_cart_items = WC()->cart->get_cart();
$current_cart_total = WC()->cart->total;
$args = array(
'customer_id' => $current_user->ID,
'date_created' => '>' . ( time() - HOUR_IN_SECONDS ),
'status' => array( 'on-hold', 'processing', 'completed' ),
'limit' => -1 // Retrieve all orders in the timeframe
);
$orders = wc_get_orders( $args );
foreach ( $orders as $order ) {
$order_items = $order->get_items();
$order_total = $order->get_total();
// Check if order total is the same
if ( $current_cart_total == $order_total ) {
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' );
return;
}
// Check if cart contains the same products
if ( wbcom_check_same_products( $current_cart_items, $order_items ) ) {
wc_add_notice( 'An order with the same products has been placed in the last hour. Please wait before placing a new order.', 'error' );
return;
}
}
}
function wbcom_check_same_products( $current_cart_items, $order_items ) {
$cart_product_ids = array_keys( wp_list_pluck( $current_cart_items, 'product_id' ) );
$order_product_ids = array_keys( wp_list_pluck( $order_items, 'product_id' ) );
sort( $cart_product_ids );
sort( $order_product_ids );
return $cart_product_ids === $order_product_ids;
}
Comments