I want to limit the number of times a user can purchase a product from a particular category. I have this code (from here) in function.php that limits the whole store to one time purchase.
add_filter('woocommerce_add_to_cart_validation','rei_woocommerce_add_to_cart_validation',20, 2);
function rei_woocommerce_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)) {
wc_add_notice( __( 'Error message here', 'woocommerce' ), 'error' );
$valid = false;
}
return $valid;
}
and I need to add a condition that the code will only apply to products from a particular category (by category name or ID).
thanks.
In the following code, you will have to replace t-shirt
by your product category (name, slug or ID):
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('t-shirt'), 'product_cat', $product_id ) ) {
wc_add_notice( __( 'Error message here', 'woocommerce' ), 'error' );
$valid = false;
}
return $valid;
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
if you need to exclude the product category you can add a !
before has_term()
like:
&& ! has_term( array('t-shirt'), 'product_cat', $product_id ) ) {