I am using the code snippet below to limit the purchase of one unique WooCommerce product per order, because of logistic reasons (multiple warehouses). I use an attribute to specify the warehouse and it would be convenient to allow customers to order multiple products if the warehouse/attribute is the same. Could someone help me with changing the code snippet?
add_filter( 'woocommerce_add_to_cart_validation', 'wc_limit_one_per_order', 10, 2 );
function wc_limit_one_per_order( $passed_validation, $product_id ) {
if ( WC()->cart->get_cart_contents_count() >= 1 ) {
wc_add_notice( __( 'This product cannot be purchased with other products. Please, empty your cart first and then add it again.', 'woocommerce' ), 'error' );
return false;
}
return $passed_validation;
}
I thought adding something like this, but I don’t know how to proceed..
$attribute = $product->get_attribute('pa_warehouse');
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$product = $values['data'];
2
Answers
Try the following revised code:
Code goes in functions.php file of your child theme (or in a plugin). It should work.
Hello i need something similar, don’t need the warehouse option. I need to block only a few products from being purchased more than once, the other products can be bought more than once. How to include only those product-ID’s?