I found this code in a previous post: Limit customers to buy a particular product multiple times within a certain time frame in WooCommerce and customized to limit the purchase of products per category (3 for regular and 1 for special promo) every year, but it doesn’t work. Can anyone have a look and let me know where the problem is? TIA!
function action_woocommerce_checkout_process() {
// Initialize
$customer_email = '';
// Get email
if ( is_user_logged_in() ) {
// Get current user
$user = wp_get_current_user();
// Get email
$customer_email = $user->user_email;
} elseif ( isset( $_POST['billing_email'] ) && ! empty ( $_POST['billing_email'] ) ) {
$customer_email = $_POST['billing_email'];
} else {
// Get billing_email
$customer_email = WC()->customer->get_billing_email();
}
// NOT empty
if ( ! empty ( $customer_email ) ) {
$time_in_years = 1;
$limit = 1;
$product_cat = 'regular'; 'special-promo';
$orders_last_year_by_customer_email = wc_get_orders( array(
'date_created' => '>' . (time() - $time_in_years ),
'customer' => $customer_email,
));
// Total (counter)
$total = 0;
// Iterating through each order
foreach ( $orders_last_year_by_customer_email as $order ) {
// Going through order items
foreach ( $order->get_items() as $item ) {
// Get product ID
$product_id = $item->get_product_id();
// Compare
if ( $specific_product_id == $product_id ) {
// Get quantity
$quantity = $item->get_quantity();
// Add to total
$total += $quantity;
}
}
}
// Show error when total >= limit
if ( $total >= $limit ) {
wc_add_notice( sprintf( __( 'Sorry, you can only purchase one time per year', 'woocommerce' ), $limit, $specific_product_id ), 'error' );
}
}
}
add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );
2
Answers
time() is a measure of SECONDS from the Unix Epoch
https://www.php.net/manual/en/function.time.php
In your code, you are subtracting 1 from the current time in seconds. Essentially looking back 1 second in time.
Wrong
What you need to do is to use the Unix Time in seconds one year ago
Right
There are many mistakes in your codeā¦ Also, you need to check cart items.
Try the following revised code version:
It should work.