I'm selling hand-painted artwork on a WooCommerce store. Since It's hand-painted artwork, The product quantity is limited to 1 (Limit purchases to 1 item per order)
I have created product variations for the artwork frame as below :
Variation 1: Wooden Frame (stock qty = 1 in variations) Variation 2: acrylic Frame (stock qty = 1 in variations)
I want to limit the order to per product/per variations basis.
Example: A User can purchase an artwork with either a wooden or acrylic frame only.
Currently, A user can add to cart artwork with both wooden & acrylic frames.
I don't want a user to purchase a unique hand-made artwork with 2 separate variations.
How can I achieve this ? Is there any function that can be used to limit this?
CodePudding user response:
Please check below global code:
add_filter( 'woocommerce_add_to_cart_validation', 'allowed_products_variation_in_the_cart', 10, 5 );
function allowed_products_variation_in_the_cart( $passed, $product_id, $quantity, $variation_id, $variations) {
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
if($cart_item['product_id'] == $product_id)
{
wc_add_notice(__('You can\'t add this product.', 'domain'), 'error');
$passed = false; // don't add the new product to the cart
// We stop the loop
break;
}
}
return $passed;
}
Also, if you have to make it for some products then you can create a custom field in the product and enable it. Then use that custom code in the front-side and do validate in the cart validation and it will perform with your defined products.
Please let me know if you find any issues.
CodePudding user response:
Here is the code that worked for me.
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_custom_add_to_cart_validation', 10, 5 );
function woocommerce_custom_add_to_cart_validation ($passed, $product_id, $quantity, $variation_id, $variations) {
$variation_id_to_delete = null;
$is_current_variation = false;
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
$product = $item['data'];
$attributes = $product->get_attributes();
if($variations['attribute_varient-id'] == $product->get_attribute('varient-id')) { // IMPORTANT = ATTRIBUTE NAMES SHOULD MATCH WITH WC ATTRIBUTES
$variation_id_to_delete = $item_key;
$is_current_variation = true;
break;
}
}
// IF IS_CURRENT_VARIATION_ID : DELETE
if ($is_current_variation){
WC()->cart->remove_cart_item($variation_id_to_delete);
}
return $passed;
}