Reputation: 83
I have 2 products in my site. Among them, for 1 product, if the user chooses more than 3 qty, I should display an error message. But for the other product, there is no limitation for the qty. How could i acheive this?
I have used the below code:
add_action( 'woocommerce_add_to_cart_validation', 'wc_add_to_cart_validation', 11, 3 );
function wc_add_to_cart_validation( $passed, $product_id, $quantity ) {
if ( $quantity > 3 ){
wc_add_notice( __( 'Only 3 or less quantities allowed, please contact us on (937) 606-4258.', 'woocommerce' ), 'error' );
$passed = false;
}
return $passed;
}
But the code reflects on both the products. I want the action to be performed only on one product Please help
Upvotes: 2
Views: 1560
Reputation: 254483
To target a specific product ID (that you will define in the code), try this instead:
add_action( 'woocommerce_add_to_cart_validation', 'conditional_add_to_cart_validation', 15, 3 );
function conditional_add_to_cart_validation( $passed, $product_id, $quantity ) {
// HERE below define your specific product ID
$specific_product_id = 37;
if ( $quantity > 3 && $product_id == $specific_product_id ){
wc_add_notice( __( 'Only 3 or less quantities allowed, please contact us on (937) 606-4258.', 'woocommerce' ), 'error' );
$passed = false;
}
return $passed;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 3