Reputation: 43
I am trying to prevent users from adding more than one item from a specific category to their cart. I found that function :
function cart_has_licence_in_it()
{
//Check to see if user has product in cart
global $woocommerce;
//assigns a default negative value
$product_in_cart = false;
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
$terms = get_the_terms($_product->id, 'product_cat');
if ($terms) {
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ($_categoryid === 23) {
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
I just changed the category ID number to 23 for this. Now I want to check if the cart already has an item from that category, and if so, remove the item from the cart and display a message :
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$categorie = get_the_terms($cart_item_data->id, 'product_cat');
$_lacat = $categorie->term_id;
if (($_lacat===23)&&(cart_has_licence_in_it())) {
wc_add_notice('You cannot add this license to your cart because there is already another license in it. Please remove the other license from your cart first.', 'error' );
$woocommerce->cart->remove_cart_item($cart_item_data->id);
}
else return $cart_item_data;
}
But it doesn't work, I don't even get the message.
As I'm new to coding WordPress and PHP in general, I am pretty sure there's a lot of mistakes in my code.
Upvotes: 0
Views: 513
Reputation: 43
After a lot of trial and error I managed to solve my problem. Here is the solution.
Please note that with this snippet, the new item overwrites the old one instead of warning the customer that they need to remove the old item.
add_filter('woocommerce_add_to_cart', 'my_woocommerce_add_to_cart', 8, 6);
function my_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
global $woocommerce;
$_category_id = 23; //put your category ID here
//Doe the item you added belong to that category ?
$_categorie = get_the_terms($product_id, 'product_cat');
if ($_categorie) {
$product_is_licence = false;
foreach ($_categorie as $_cat) {
$_lacat = $_cat->term_id;
if ($_lacat === $_category_id) {
$product_is_licence = true;
}
}
}
//If it does, remove all items from same category from cart
if($product_is_licence){
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $value) {
$_product = $value['data'];
$_thisID = $_product->id;
$terms = get_the_terms($_product->id, 'product_cat');
if ($terms) {
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if (($_categoryid === $_category_id)&&($product_id !== $_thisID)) {
$woocommerce->cart->remove_cart_item($cart_item_key);
$message = sprintf( '%s has been removed from your cart.',$_product->get_title()); //displays the removal message
wc_add_notice($message, 'success');
}
}
}
}
}
}
Upvotes: 2