Skip to content

Instantly share code, notes, and snippets.

@blackmann
Forked from lukecav/functions.php
Created July 24, 2018 12:25
Show Gist options
  • Save blackmann/9ec4048c859ce213b970b118490e1251 to your computer and use it in GitHub Desktop.
Save blackmann/9ec4048c859ce213b970b118490e1251 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