php - Woocommerce: add free product if cart has 3 items -
what i'm trying add free product if user have 3 product in cart. choosed woocommerce_add_cart_item
hook this. here code :
add_filter('woocommerce_add_cart_item', 'set_item_as_free', 99, 1); function set_item_as_free($cart_item) { global $woocommerce; $products_with_price = 0; foreach ( $woocommerce->cart->get_cart() $cart_item_key => $values ) { if($values['data']->price == 0) { continue; } else { $products_with_price++; } } if( $products_with_price > 1 && $products_with_price % 3 == 1) { $cart_item['data']->set_price(0); return $cart_item; } return $cart_item; }
i tried $cart_item['data']->price = 0;
doesn't work out either :( there wrong or maybe there other way done? thanks.
try modified code: (have changed condition.)
add_filter('woocommerce_add_cart_item', 'set_item_as_free', 99, 1); function set_item_as_free($cart_item) { global $woocommerce; $products_with_price = 0; foreach ( $woocommerce->cart->get_cart() $cart_item_key => $values ) { if($values['data']->price == 0) { continue; } else { $products_with_price++; } } if( $products_with_price >= 3 && $products_with_price % 3 == 1) { $cart_item['data']->set_price(0); return $cart_item; } return $cart_item; }
if don't want add free product again after user purchases 3 products above existing cart remove " && $products_with_price % 3 == 1
" last condition.
Comments
Post a Comment