0

So in short, we're planting 1 tree for every product sold (we do have a few exceptions). I want this tree product to be added to the cart (as freebie) so people get the feeling they're planting trees when shopping with us.

Now, I found this answer:

Auto add or remove a freebie product from cart in Woocommerce

But this code only allows one freebie to be added to the cart, no matter the amount of products that is in the cart.

I altered the code slightly, but it's not fully functional as I need it to be. Who can help me complete the code so it's fully functional?

function add_remove_freebie( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $freebie_id = 5077; // <== HERE set the freebie product ID
    $has_others = false;
    $cartAmount = $cart->get_cart_contents_count();

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Added Woocommerce compatibility version
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();

        if( $product_id == $freebie_id ) {
            // Freebie is in cart
            $freebie_key = $cart_item_key;
        } else {
            // Other items are in cart
            $has_others = true;
        }
    }
    // If freebie product is alone in cart we remove it
    if( ! $has_others && isset( $freebie_key ) ){
        $cart->remove_cart_item( $freebie_key );
    } elseif ( $has_others && ! isset( $freebie_key ) ) {
        $cart->add_to_cart($freebie_id, $cartAmount);
    }
}
sebas6691
  • 41
  • 6
  • Is this running on `woocommerce_before_calculate_totals`? – T Paone Nov 15 '19 at 19:21
  • I placed the code in functions.php I'm not much of an experienced programmer in php/woocommerce, but on line 6 of this code is the `woocommerce_before_calculate_totals` – sebas6691 Nov 16 '19 at 06:35
  • Do you have it a line that does `add_action('woocommerce_before_calculate_totals', 'add_remove_freebie');` in functions.php ? – T Paone Nov 18 '19 at 13:49
  • I checked, but I do not have that line of code in the functions.php of my child theme. – sebas6691 Nov 18 '19 at 17:01
  • You'll need that `add_action`, otherwise the function will never run. – T Paone Nov 18 '19 at 22:26
  • But the function is running.... but it only allows one freebie to be added to the cart, no matter the amount of products that is in the cart. – sebas6691 Nov 19 '19 at 13:10
  • Oops, sorry about that. It does have it: add_action( 'woocommerce_before_calculate_totals', 'add_remove_freebie', 50, 1 ); – sebas6691 Nov 19 '19 at 16:17

0 Answers0