Skip to content

Instantly share code, notes, and snippets.

@lukecav
Created September 22, 2016 04:08
Show Gist options
  • Save lukecav/19c4e328466a6e62f440eb857886bf78 to your computer and use it in GitHub Desktop.
Save lukecav/19c4e328466a6e62f440eb857886bf78 to your computer and use it in GitHub Desktop.
Need Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another 1 is added then it should remove the previous 1
function check_if_cart_has_product( $valid, $product_id, $quantity ) {
if(!empty(WC()->cart->get_cart()) && $valid){
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if( $product_id == $_product->id ) {
unset(WC()->cart->cart_contents[$cart_item_key]);
}
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment