I am trying to remove particular product from cart via code. I only see the empty cart option which is clear all the product in cart, but i want to clear particular product in cart page.
For example:
Let say I have added two products to cart but i want cart behavior should be neither or nor mean only one product should be in cart.
If product 1 is in cart then product 2 should not allow to add in cart. If product 2 is in cart then product 1 should not allow.
I tried little set of code but i can’t find the exact hook to do this actual behavior. What i am trying is instead of empty entire cart, I load the cart content which is in array of values just unset particular array using cart item key, and to load remaining content to cart. But looks like is not works for me.
function cf_alter_cart_content($value) {
global $woocommerce;
$cart_contents = $woocommerce->cart->get_cart();
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $value) {
if ($value['product_id'] == '77') {
unset($cart_contents[$cart_item_key]);
unset($value['data']);
}
return $value['data'];
}
}
//add_action('wp_head', 'cf_alter_cart_content');
add_filter('woocommerce_cart_item_product', 'cf_alter_cart_content', 10, 1);
May be is there any easy way to achieve this? Not sure any suggestion would be great.
I’m using the
woocommerce_before_cart
filter for a similar setup where people in certain groups aren’t allowed to order specific product skus. I hope this helps. You would likely want to create a custom field in each product that would be something like a comma delineated list of other skus/post_ids that it wouldn’t be allowed to be ordered with.This code checks the first group that the user is associated with (in my site’s case they only ever have 1 group). The disallowed_product_skus is the list of skus that the group for the user isn’t allowed to purchase.