×

 

Home Contact Us Payments SC Commerce SC Commerce Docs SC Commerce Snippets

Simply Computing

We make websites. Simple.

Add a gift item to the cart when another item added

You may want to include a free “gift” or bonus item when a certain product has been added to the cart. With this code, if a product with a set ID is added to the cart, another product automatically gets added as well. The second product should have price = 0 if it is to be given away.  If the product is only to be gifted when the first one is added and not available separately then it should be set to “hidden”.

		/**
 * Adds a gift item to the cart when another item has been added
 */

// If a product with set ID is added to the cart, another product automatically gets added as well.
// The second product should have price = 0 if it is to be given away.
// If the product is only to be gifted when the first one is added, it should also be set to “hidden”.
// https://www.businessbloomer.com/woocommerce-buy-1-product-add-free-product-cart-programmatically/
 
add_action( 'template_redirect', 'scc_add_gift_if_id_in_cart' );
 
function scc_add_gift_if_id_in_cart() {
 
   if ( is_admin() ) return;
   if ( WC()->cart->is_empty() ) return;
 
   $product_bought_id = 32;
   $product_gifted_id = 57;
 
   // see if product id in cart
   $product_bought_cart_id = WC()->cart->generate_cart_id( $product_bought_id );
   $product_bought_in_cart = WC()->cart->find_product_in_cart( $product_bought_cart_id );
 
   // see if gift id in cart
   $product_gifted_cart_id = WC()->cart->generate_cart_id( $product_gifted_id );
   $product_gifted_in_cart = WC()->cart->find_product_in_cart( $product_gifted_cart_id );
 
   // if not in cart remove gift, else add gift
   if ( ! $product_bought_in_cart ) {
      if ( $product_gifted_in_cart ) WC()->cart->remove_cart_item( $product_gifted_in_cart );
   } else {
      if ( ! $product_gifted_in_cart ) WC()->cart->add_to_cart( $product_gifted_id );
   }
}
	
   View Raw Code ID: 93470