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);
}
}