Add Giveaway to WooCommerce Cart

If you would like to give your supporters a free giveaway (freebee), you can use the following code. Just add the action in the functions.php file of your theme. Tip: You can of course also use the free Code Snippets plugin instead.

For the code to work, you have to enable the option “Allow more than one product in cart” in the WooCommerce settings -> tab “Donations”. Please remember to specify the product ID of the giveaway and the minimum donation amount on lines 8 & 9.

// Add free giveaway to cart if amount is high enough
add_action('woocommerce_before_calculate_totals', function($cart) {
  if (is_admin()) {
	  return;
  }

	// TODO
	$free_product_id = 368;
	$targeted_subtotal = 50;
	
	$cart_total = 0;

  // find giveaway in cart
  foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
    if ($free_product_id == $cart_item['product_id']) {
      $free_key = $cart_item_key;
      $free_qty = $cart_item['quantity'];
      $cart_item['data']->set_price(0);
    } else if ( isset( $cart_item["wcdp_donation_amount"] ) && WCDP_Form::check_donation_amount($cart_item["wcdp_donation_amount"])) {
		$cart_total += $cart_item["wcdp_donation_amount"];
	}
  }

  // If donation amount match and free product is not already in cart, add it
  if (!isset($free_key) && $cart_total >= $targeted_subtotal) {
    $cart->add_to_cart($free_product_id);
  }
  // If donation amount doesn't match and free product is already in cart, remove it
  else if (isset($free_key) && $cart_total < $targeted_subtotal) {
    $cart->remove_cart_item($free_key);
  }
  // Keep free product quantity to 1.
  else if (isset($free_qty) && $free_qty > 1) {
    $cart->set_quantity($free_key, 1);
  }
}, 10, 1);