php - Conditionally adding or removing a free product in cart -
i've function in woocommerce add automatically cart free gift.
i add based on minimum quantity of 15
i've code works, when update cart don't remove item if quantity not 15.
how can automatic remove product when update cart if total id different 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) { // nothing } else { $found = false; if ( sizeof( $cart ) > 0 ) { foreach ( $cart $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
is better use woocommerce_before_calculate_totals
dedicated woocommerce hook handle changes customers can on cart page (removing items, updating quantities).
this code:
add_action( 'woocommerce_before_calculate_totals', 'wcsg_adding_promotional_product', 10, 1 ); function wcsg_adding_promotional_product( $cart_object ) { if(!is_cart()) return; $promo_id = get_option('wcsgproduct'); // getting id of promotional product $targeted_cart_items = 15; // <=== set here targeted number of items in cart $cart_count = $cart_object->cart_contents_count; // items in cart $has_promo = false; if ( !$cart_object->is_empty() && is_cart() && !empty($promo_id)){ // iterating through each item in cart foreach ($cart_object->cart_contents $key => $cart_item ){ // if promo product in cart if( $cart_item['data']->id == $promo_id ) { $has_promo = true; $promo_key= $key; } } //if promo product not in cart , targeted item count reached, add it. if( !$has_promo && $cart_count >= $targeted_cart_items ) $cart_object->add_to_cart($promo_id); // if promo product in cart , targeted item count not reached, remove it. if( $has_promo && $cart_count <= $targeted_cart_items ) $cart_object->remove_cart_item($promo_key); } }
code goes on function.php file of active child theme (or theme) or in plugin file.
this codes tested , works.
based on: adding promotional product when cart amount reached
related thread: woocommerce - auto add or auto remove freebie product cart
Comments
Post a Comment