Skip to content

Instantly share code, notes, and snippets.

@vagelisp
Last active August 4, 2023 13:37
Show Gist options
  • Save vagelisp/5f0f1530d3910eb8a2a5b3c43dc32559 to your computer and use it in GitHub Desktop.
Save vagelisp/5f0f1530d3910eb8a2a5b3c43dc32559 to your computer and use it in GitHub Desktop.
WooCommerce - Function to restrict users from placing multiple orders per hour
<?php
// Function to restrict users from placing multiple orders per hour
function restrict_orders_per_hour_product_notice() {
// Get the current user's ID.
$user_id = get_current_user_id();
// Retrieve all orders for the current user.
$orders = wc_get_orders( array(
'numberposts' => -1,
'orderby' => 'date',
'order' => 'DESC',
'customer_id' => $user_id,
) );
if ( $orders ) {
// Get the latest order for the user.
$latest_order = current( $orders );
// Calculate the time difference between the current time and the latest order's creation time.
$time_difference = time() - strtotime( $latest_order->get_date_created()->date_i18n( 'Y-m-d H:i:s' ) );
// Calculate the remaining time until the user can place another order (maximum one order per hour).
$remaining_time = 60 - round( $time_difference / 60 ); // Convert seconds to minutes.
// If the user has placed an order within the last hour, display the notice.
if ( $time_difference < 3600 ) {
echo '<div class="woocommerce-info">';
printf( __( 'You can only place one order per hour. Please try again in %d minute(s).', 'woocommerce' ), $remaining_time );
echo '</div>';
// Disable "Add to Cart" buttons on product pages to prevent additional orders.
add_filter( 'woocommerce_is_purchasable', '__return_false' );
}
}
}
// Hook the function to display the restriction notice and disable "Add to Cart" buttons on product pages.
// The priority (5) ensures this code runs early before other elements on the product page.
add_action( 'woocommerce_before_single_product_summary', 'restrict_orders_per_hour_product_notice', 5 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment