I've a function in woocommerce that add automatically to cart a free gift.
I would like to add this based on minimum quantity of 15
i've this code that works, but when i update the cart don't remove the item if the quantity is not 15.
How I can automatic remove product when I update the cart if total id different to 15 ?
}
//add_action( 'init', 'wcsg_add_product_to_cart' );
add_action( 'wp_loaded', 'wcsg_add_product_to_cart', 99 );
function wcsg_add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
//calcoliamo quanti prodotti ci sono nel carrello
$totalecarrello = $woocommerce->cart->cart_contents_count;
echo "<script type='text/javascript'>alert('$totalecarrello');</script>";
$cart = WC()->cart->get_cart();
$wcsgProduct = '0';
$wcsgProduct = get_option('wcsgProduct');
$product_id = $wcsgProduct;
if ($product_id== '0' || $product_id == NULL) {
// do nothing
} else {
$found = false;
if ( sizeof( $cart ) > 0 ) {
foreach ( $cart as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
//controlliamo quanti prodotti ci sono
if ( ! $found && $totalecarrello == 15 )
//se sono 15 aggiungiamo il prodotto free
WC()->cart->add_to_cart( $product_id );
$message = $woocommerce->cart->cart_contents_count;
echo "<script type='text/javascript'>alert('$message');</script>";
$totalecarrello = $woocommerce->cart->cart_contents_count;
//altrimenti no
} else {
//WC()->cart->add_to_cart( $product_id );
WC()->cart->remove_cart_item($product_id);
}
}
}
}
Thanks for help