WordPress.org

Forums

[Plugin: Woocommerce] Add free product if cart has 3 items (2 posts)

  1. Molod
    Member
    Posted 1 year ago #

    What I'm trying to do is to add free product if user have 3 product in cart. I choosed woocommerce_add_cart_item hook for this. Here is my 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() as $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 also tried $cart_item['data']->price = 0; but it doesn't work out either :( Is there is something I do wrong or maybe there is some other way to get this done? Thanks.

  2. Gravuj Miklos Henrich
    Member
    Posted 1 year ago #

    I am facing the same situation.

Topic Closed

This topic has been closed to new replies.

About this Topic