I want to let customers buy only one product from a defined category. All products are priced as 0 (zero). Only delivery fee is charged.
I referred to the same scenario and tried this code. But this code fails for not logged in users. When I try multiple purchases I have no matter of buying. Want to limit after the first successful attempt of a purchase. I am using the child theme functions.php
file.
Note: customers do not need to register in the website before doing a purchase.
add_filter('woocommerce_add_to_cart_validation','filter_add_to_cart_validation',20, 2);
function filter_add_to_cart_validation($valid, $product_id){
$current_user = wp_get_current_user();
if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id) && has_term( array('free-giveaway'), 'product_cat', $product_id ) ) {
wc_add_notice( __( 'You already bought an item. Let others to buy as well.', 'woocommerce' ), 'error' );
$valid = false;
}
return $valid;
}