Many times we face an issue regarding exclusive addition of a product in cart. For example, if a product say A is in cart then customer cannot add any new product B that is called exclusive products. In this case, customer is bound to either remove that very product A from cart or place order for it. So, here we will put some WooCommerce Cart Restriction.
WooCommerce Cart Restriction With ID
Lets say a product named A is exclusive and we know it’s ID i.e., product id is known then we can approach like this:-
<?php class Exclusive_Product{ function __construct(){ add_filter( 'woocommerce_before_cart', array($this, 'check_cart_product') ,10, 1); } public function check_cart_product( $cart_item_data ){ global $woocommerce; $id; // exclusive product id$cart
= WC()->cart;
$get_cart = WC()->cart->cart_contents; //all cart contents if(!empty($get_cart)){ foreach($get_cart as $key => $value ){ $product_id = $value['product_id']; if($product_id == $id){ //comparing exclusive product id i.e."$id" with all cart products id's i.e."$product_id" $woocommerce->cart->empty_cart(); WC()->cart->add_to_cart($id); } } return WC()->cart->cart_contents; } } }
As we can see WooCommerce already provides a filter named “woocommerce_before_cart” so we have to load our function on that very hook. The filter provides cart data, so we will get all cart data and perform check for the exclusive product A with id “$id” among all products in cart. If the id’s matches then we will empty cart and add the exclusive product only in cart else we will do no changes in cart.
WooCommerce Cart Restriction With Title
There is also a situation when we don’t know the id of exclusive product so in that case we can approach like this:-
<?php class Exclusive_Product{ function __construct(){ add_filter( 'woocommerce_before_cart', array($this, 'check_cart_product') ,10, 1); } public function check_cart_product( $cart_item_data ){ global $woocommerce; $exclusive_product = get_page_by_title('Product Name', OBJECT, 'product'); $id = $exclusive_product->ID; //ID of exclusive product$cart
= WC()->cart;
$get_cart = WC()->cart->cart_contents; //all cart contents if(!empty($get_cart)){ foreach($get_cart as $key => $value ){ $product_id = $value['product_id']; if($product_id == $id){ //comparing exclusive product id i.e."$id" with all cart products id's i.e."$product_id" $woocommerce->cart->empty_cart(); WC()->cart->add_to_cart($id); } } return WC()->cart->cart_contents; } } }
I hope its quite easy to understand the above code. We can simply get the product details by using get_page_by_title() and then we can ghet it’s ID.
We also face some cases where we don’t know id and title of custom post type. So, in such cases we can perform the same using “post type”.
Support
Still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/
Thanks for Your Time! Have a Good Day!
Thanks!