Re: Automatically add free item to cart

Solved

How can I auto-add a free item to the cart when a spending threshold is met?

scoresfilm
Visitor
2 0 2

Hello,

 

Is there a way to have an item automatically added to an order when a certain threshold is met?

 

We would like to give customers a free canvas tote (normally $10) when they spend $80 at our store. I've tried buy x, get y free before, but sometimes customers forget to add to cart in order to get the free gift, so we would like to automate the process.

 

Any thoughts?

Accepted Solution (1)
Greta
Shopify Staff (Retired)
1242 132 169

This is an accepted solution.

Thanks for jumping in, @KendallVernon!

 

I passed your feedback along to our team. I also recommend contacting our Plus Support team to see if they have any app suggestions for your store in the meantime. 

 

Cheers!

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

View solution in original post

Replies 41 (41)

Greta
Shopify Staff (Retired)
1242 132 169

Hi, @scoresfilm!

Thank you for your post. I can definitely suggest some apps that provide your customers with a free item as part of their purchase.

When searching for free gift apps in our app store, I found some great options that specifically mention that the gifts are automatically added when the customer meets the criteria you define. Check those out here:

If you’re new to third party apps, I recommend checking out this guide which goes over all the details you might want to know about them (https://bit.ly/3HshOOm). You can also check out these two help documents regarding how to work with apps (for example, how to install/uninstall them and how to view an app’s invoice) and how to get support

I hope this helps!

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

James46
Tourist
8 0 46

Why doesn't Shopify offer this feature? The 'Buy x, Get y' feature is useless. 

Joseph_Symond
Tourist
7 0 9

Shopify will wait to see if it becomes popular first. Then they will disconnect the 3rd party software, and replace it with a 'FREE' version of their own that doesn't work half as well. As they did with 'KIT' and many others.

James46
Tourist
8 0 46

To dd to my last, all these apps are very expensive for just one feature customers are looking to add. You guys should not be forcing customers to expend additional cost because your current offering is deficient. 

Greta
Shopify Staff (Retired)
1242 132 169

Hi, @James46!

 

Thank you for sharing your feedback. I definitely understand wanting this feature offered by Shopify directly, and I'm happy to pass your thoughts along to our developers. Feedback like this is how we determine what features to create and improve. I can't guarantee this change will be implemented, but if it is, it will be added to the Shopify Changelog

 

Thanks again for taking the time to share your thoughts with me!

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

andydean
Visitor
1 0 3

Can you add the ability for your Pro customers, which includes me, to vote on features and then release (where possible) in that order, this one is a common feature that we all want, and we are paying for through other apps.

Greta
Shopify Staff (Retired)
1242 132 169

Hi, @andydean!

 

Thank you for your comment — that's a great idea! By sharing your feedback here or with our live support team, you are essentially "voting" on wanting that feature. Every time a piece of feedback is shared, our developers know that one more merchant wants that feature and they can prioritize it. So you may not see anything like this publicly, but we're constantly reviewing feedback behind the scenes!

 

Please let me know if you have any other questions. 

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

Jekyllhyde
Visitor
1 0 2

Also came here just to say we would really like this feature to be added. Getting the customer to add it to their cart is very difficult and when they don't do it properly we have angry customers on our hands. 

Greta
Shopify Staff (Retired)
1242 132 169

Hi, @Jekyllhyde!

 

Thank you for adding your feedback, I understand how this feature would be useful for your store. I've passed your insights along to our developers!

 

Please let me know if there's anything else I can help you out with. 

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

R-Daneel
Shopify Partner
17 0 19

Hi @Greta :

We really appreciate your reply and your adding this to the feature wish list. This is one that we really want as well. From all of the postings I see on the internet, I'm guessing it's very in demand.

In addition, we would like to be able to have more than one buy x get y discount active at a time.

 

For us, we find that third party apps are very heavy and often slow down our store speed. Additionally, while the sales pitch presents these apps as perfect, we are always finding limitations once we deploy them.

We'd really like for Shopify to be more versatile, in general. Maybe you should present another tier which is more feature rich.

 

Thanks!

Andrew
Shopify Staff (Retired)
1746 173 326

Thanks for your feedback! I've shared that internally. Shopify is always upgrading the platform, which is why we released 100+ product updates earlier this year. 

What plan are you currently on? We do have an enterprise pricing plan called Shopify Plus which is available on a 12-month contract and starts from $2000 per month as it caters to the needs of larger businesses. Is that something you might be interested in? 

To learn more visit the Shopify Help Center or the Community Blog.

R-Daneel
Shopify Partner
17 0 19

Thanks, @Andrew , for the info. We're actually already on the Shopify Plus plan. We appreciate all of the product updates. We end up doing a lot of custom coding, however, and find that the customizable interface falls short of the requirements we're asked to meet regularly. Having been part of a team that built a multi-store system similar to Shopify, I understand, however, how hard it is to meet everyone's requests. So I appreciate your putting auto-add free item to cart on the wish list. If you can also add allowing more than one active buy x get y free discount at a time to that list, it is greatly appreciated.

 

Thanks!

ryancrawford84
Visitor
1 0 3

I am also disappointed that this service isn't automatically included. 

Greta
Shopify Staff (Retired)
1242 132 169

Hey, @ryancrawford84!

 

Thanks for sharing your thoughts. I've passed along your feedback to our developers, and you can keep up with platform changes by checking out the Shopify Changelog.

 

Please let me know if you have any other questions!

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

Deepak30
Visitor
2 0 5

Just that one thing of not automatically adding the eligible free product to cart makes this entire "buy x, get y free" useless feature.  Shopify please think of all use case before launching a feature.

Now you shouldn't delay fixing this feature. Its not something good to have, its a must have. Treat it as a BUG.

Greta
Shopify Staff (Retired)
1242 132 169

Hi, @Deepak30!

 

I appreciate you sharing your feedback and I certainly understand where you're coming from. I'm happy to pass your thoughts along to our developers. 

 

Please let me know if there's anything else I can help you with. 

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

KendallVernon
Visitor
1 0 3

I created an account just to comment here to hopefully cast another "vote" for this feature. I agree with some of the other commenters that not having this feature is more of a bug than a feature request. Currently paying a billion dollars for Shopify Plus and can't automatically add a free item to my customers' cart is pretty wack. Ty.

Greta
Shopify Staff (Retired)
1242 132 169

This is an accepted solution.

Thanks for jumping in, @KendallVernon!

 

I passed your feedback along to our team. I also recommend contacting our Plus Support team to see if they have any app suggestions for your store in the meantime. 

 

Cheers!

Greta | Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

Joseph_Symond
Tourist
7 0 9

I see 3-years of hearing/reading 'I passed your feedback along to our team', yet no solution to this issue. And pushing an app as a solution to a problem caused by Shopify is not a solution at all. This just leads us to believe it's all about the money. Steering customers into upgrading to Pro or Enterprise, only to find out that they have the same issues. Looks like Shopify is following the Intuit model. However, Intuit has a monopoly. Shopify does not. Disappointing. But why care what I and the others here have to say eh? How many of us will it take to motivate Shopify for a real solution that doesn't require an upgrade, or push us to yet another app?

Super-
Visitor
1 0 0

Please add the feature expressed by many here. The current manual way is I agree useless. Ty

Nevada
Visitor
1 0 3

When I saw that this request had a solution, I didn't expect the solution to be No Solution and pay more money for another plugin! It's been about 6 months, is this going to be added any time soon? I would assume the admin screen would be if {'discounted value' = 'Free'} then {'add option of auto cart' = 'True'} I am sure that there is extra work in the back end code, but please, this shouldn't be a huge addition to the changelog. Any idea when this will be added?

 

Zoe2017
Visitor
1 0 0

This is marked as Solved… what’s the Shopify Solution?

mihnsen
Shopify Partner
6 0 0

 

Screenshot 2024-11-28 at 16.07.08.png

 

You guys should check out the solution from our team (qikify). It does exactly what is described in the topic.

https://apps.shopify.com/qikify-upsell-bundle

I'm co-founded the team behind: qikify, teeinblue, tepo,...
Marcus_Frasier
Excursionist
17 0 7

Honestly, this is one of the reasons I keep rejecting their attempts to get us to upgrade. Why am I going to pay that much per month and still have to code my own solutions to their shortcomings? The code will work just as fine on a non-pro plan, so I'll just pay myself with pats on the back.

jonavalt
Tourist
3 0 2

Came here to throw in my vote for this addition as well. It has to be a BUG that an auto add to cart feature wasn't included natively. I already pay so much for add-ons on top of my base subscription, I can't believe I have to find ANOTHER add-on to pay for to get this to work as intended.

 

Way to not consider the user experience at all in this case.

bshum1
Tourist
3 0 2

Hi there 

 

I'm trying to do the same thing. Did you find a suitable solution?

 

THanks

Bonnie

binal_identix
Shopify Partner
681 60 119

Hello @scoresfilm & @bshum1,

Hope you are doing well.

To meet your requirement, iCart Cart Drawer Cart Upsell app is the best fit.

iCart Cart Drawer Cart Upsell App


- If you find the solution helpful, please accept and like it
- To learn more visit www.identixweb.com

CheckoutLinks
Shopify Partner
53 1 2

Hi there @scoresfilm & @bshum1!

 

HypeCart can do exactly what you're asking for, and even more.

 

I would suggest to check it out and if you have any questions at all just send us an email on hello@hypecart.co or through the chat in the app.

 

All the best!

Checkout Links - Create shopable links to sell anywhere
App Store - Demos - Website

GFW-webAdmin
Shopify Partner
17 1 4

Dealing with the same thing. 

We are including a free digital download with every purchase, and want to restrict customers from seeing the digital download until after purchase. 

I found this 100% free app (not affiliated) that is simple but gets the job done. 

 

https://apps.shopify.com/cartbot-auto-add-to-cart

 

Good luck!

Deepak30
Visitor
2 0 5

Just that one thing of not automatically adding the eligible free product to cart makes this entire "buy x, get y gree" useless feature.  Shopify please think of all use case before launching a feature.

Now you shouldn't delay fixing this feature. Its not something good to have, its a must have. Treat it as a BUG.

dprf
Visitor
1 0 0

I can only agree with the previous posts in this thread. This is a very basic feature that should be included no matter if you are on Plus or not, at least now I know upgrading will not help me.

welcomebrand
Shopify Partner
77 1 115

Just adding another vote for the "it's insane I've just had to spend another $40/month on an app to do basic Buy X, Add Y functionality" on my site

aditya58singh
Shopify Partner
34 2 6

Yes, you can achieve this functionality using the "Cart Drawer Upsell & Free Gift" app. This app allows you to set up automated triggers so that when customers meet a certain threshold, such as spending $80 will be automatically added to their cart.

 

By automating this process, you can ensure that customers receive their free gift without having to remember to add it manually. This not only improves customer satisfaction but also helps increase the average order value (AOV) and conversion rate on your store.

- Helpful? Like and Accept a solution.
- Cart Drawer Upsell & Free Gift Boost conversions & AOV with upsell-cross sell, free gifts & add-ons with customizable cart drawer.

Sales Countdown Timer Bar create urgency with count down timer, navigation menu with images and lot more.

PackLabelShip
Shopify Partner
36 1 0

Hey Everyone,

 

This is a situation a ton of people use our app for. We make it super simple to add a 'forgotten' rule so if an order is placed that the Buy X Get Y should apply to and no free item is added you can include the free item after all and save yourself a bunch of time and money on customer support, shipping cost to get them their 'forgotten' free gift, and brand image.

 

We allow you to check if a discount code is applied, the product contains or doesn't contain an item with a tag or specific product and variant.

 

Link to the app: https://apps.shopify.com/pls-smart-pack-ship

 

And a quick video demoing and explaining the setup and functionality: 

 

Thanks,

Tom

Putting Custom Packaging and Order Inserts back in the Merchant's hands!
Marcus_Frasier
Excursionist
17 0 7

"A ton of people" but 0 reviews in 5 months?

PackLabelShip
Shopify Partner
36 1 0

Hey Marcus,

 

I guess "a ton" is subjective in this case! Hope you're willing to check out the free trial. I'm just sharing the experience our merchants have had, and offering a potential solution. I certainly should do a better job of asking for reviews, I've just been happy with people using it!

 

Cheers,

Tom

Putting Custom Packaging and Order Inserts back in the Merchant's hands!
PackLabelShip
Shopify Partner
36 1 0

Well, Well, Well @Marcus_Frasier looks who's back with one review! 

PackLabelShip_0-1714080351115.png

 

Putting Custom Packaging and Order Inserts back in the Merchant's hands!
Marcus_Frasier
Excursionist
17 0 7

LMAO! Watch out, we got a bad@$$ over here! Congrats though 🙂

yhonig43
Shopify Partner
1 0 0

@scoresfilm did you find a solution to this friend?

sarawl
Shopify Partner
40 1 1

Hi there,

 

I'd like to also recommend app Selly to help you to offer free gifts automatically based on cart subtotal:

 

Screen Shot 2024-11-17 at 1.33.56 AM.png

 

Screen Shot 2024-11-17 at 1.34.51 AM.png

Screen Shot 2024-11-17 at 1.40.04 AM.png

 

In case there are some gift options, customers can select the option they like.

 

You can also offer free gifts based on quantity via the app.

 

The app interface is customizable and the app support is ready to help:

 

https://apps.shopify.com/selly

 

There are also other features such as bundle, recommendation, motivator...

 

Dmns
Shopify Partner
1 0 0

 

 

Instruction for Creating a Gift Product

I managed to implement it without using any additional apps!

Below is the instruction to make it easier to replicate this process.


1. Create Two Metafields for Products:

  • Redirect to Product: custom.redirect (Single line of text)
  • Hide from Search: seo.hidden (Single line of text)

If there is an error when creating the seo.hidden metafield, install the free app "Edit Metafields," which allows you to set this using a different approach.


2. Edit layout/theme.liquid

Add the following inside <head></head>:

{% if product.metafields.custom.redirect != blank %}
<meta http-equiv="refresh" content="0; url={{ product.metafields.custom.redirect }}">
{% endif %}

3. Create a Duplicate Product:

  • Make a copy of the original product.
  • Add "GIFT" or "FREE" at the end of the product title.

3.1 Set the Price to 0:

  • Set the price of the newly created gift product to 0.

3.2 Set "Hide from Search" to 1:

  • If you were unable to create this metafield manually, you can set it using an app:
    • Click the More actions button (top right) → select Edit Metafields.
    • Fill in the following fields:
      • Namespace: seo
      • Key: hidden
      • Value: 1

4. Get the JSON URL of the Product:

Use the following URL format:

https://your-shopify-store.com/products/<product_address>.json

Example:

https://hiutdenim.co.uk/collections/washed-black/products/italian-black-organic-the-work-straight-fit.json

4.1 Find Variant ID in JSON:

  • Look inside the JSON file for Variant id, for example:
[{"id": 41175859724358, "product_id": ...}]
  • The required Variant ID: 41175859724358

5. Create the snippets/free-gift.liquid File:

 

{% comment %}
/**
 * Automatic Free Gift with Purchase
 * 
 * This snippet adds a free gift to the cart when the cart total exceeds a specified threshold.
 * The gift is automatically added/removed as the cart changes, and the functionality can be
 * toggled on/off through the Shopify admin.
 * 
 * Features:
 * - Automatically adds specified product as a free gift when cart total exceeds threshold
 * - Automatically removes the free gift when cart total falls below threshold
 * - Can be enabled/disabled via a Shopify liquid variable
 * - Handles various cart update scenarios including AJAX updates
 * - Hides quantity controls for the free gift in cart
 */
{% endcomment %}

{% assign enable_free_gift = false %}  {% comment %} Set to true to enable free gift functionality {% endcomment %}
{% assign product_variant_id = 41175859724358 %}  {% comment %} The variant ID of the free gift product {% endcomment %}
{% assign threshold = 90000 %}  {% comment %} Cart threshold in cents (900 USD) {% endcomment %}

<style>
  /* 
   * Hide quantity adjustment controls for the free gift product in cart
   * This prevents customers from changing the quantity of the free gift
   */
  [data-key^="{{ product_variant_id }}"] .js-qty__wrapper {
    display: none !important;
  }
</style>

<script>
/**
 * Free Gift Management System
 * 
 * This script handles the automatic addition and removal of a free gift
 * product based on the cart total and a defined threshold.
 */

// Prevents multiple concurrent executions of the gift logic to avoid race conditions
let isGiftProductLogicRunning = false;

// Get the enable/disable setting from Shopify Liquid
const enableFreeGift = {{ enable_free_gift }};

/**
 * Initialize the script when the page is fully loaded
 */
document.addEventListener('DOMContentLoaded', function() {
  console.log('Gift product script initialized');
  console.log('Free gift feature is ' + (enableFreeGift ? 'enabled' : 'disabled'));
  
  // Run the gift logic once on page load
  runGiftProductLogic();
  
  // Set up event listeners to detect cart changes
  setupCartUpdateListeners();
  
  // Intercept cart additions to detect new products
  interceptAddToCart();
});

/**
 * Intercepts fetch API calls to detect when products are added to cart
 * This helps catch cart updates that might not trigger standard events
 */
function interceptAddToCart() {
  const originalFetch = window.fetch;
  window.fetch = function() {
    const args = arguments;
    const url = args[0];

    // If this is a cart addition, trigger our logic
    if (typeof url === 'string' && url.includes('/cart/add.js')) {
      console.log('Product added to cart detected via fetch:', args);
      runGiftProductLogic();
    }

    // Call the original fetch function
    return originalFetch.apply(this, arguments);
  };
}

/**
 * Sets up multiple event listeners to detect cart updates via different methods
 * This ensures the gift logic runs regardless of how the cart is updated
 */
function setupCartUpdateListeners() {
  // Listen for native cart request complete events
  document.addEventListener('cart.requestComplete', function() {
    console.log('Cart update detected via cart.requestComplete event');
    runGiftProductLogic();
  });

  // Listen for jQuery-based cart update events (used by many themes)
  if (typeof jQuery !== 'undefined') {
    jQuery(document).on('cart.loaded cart.requestComplete cart:refresh cart:updated', function(event) {
      console.log('Cart update detected via jQuery event:', event.type);
      runGiftProductLogic();
    });
  }

  // Fallback: Poll the cart state regularly to catch any missed updates
  let lastCartState = JSON.stringify({{ cart | json }});
  setInterval(function() {
    fetch('/cart.js')
      .then(response => {
        if (!response.ok) throw new Error('Failed to fetch cart data');
        return response.json();
      })
      .then(cart => {
        const currentCartState = JSON.stringify(cart);
        if (currentCartState !== lastCartState) {
          console.log('Cart update detected via polling');
          lastCartState = currentCartState;
          runGiftProductLogic();
        }
      })
      .catch(error => console.error('Polling error:', error));
  }, 3000); // Check every 3 seconds
}

/**
 * Main function that manages the free gift logic
 * This ensures the correct products are in the cart based on the current state
 */
function runGiftProductLogic() {
  // Prevent multiple simultaneous executions
  if (isGiftProductLogicRunning) return;
  isGiftProductLogicRunning = true;

  console.log('Running gift product logic');
  
  // Get current cart data
  fetch('/cart.js')
    .then(response => {
      if (!response.ok) throw new Error('Failed to fetch cart data');
      return response.json();
    })
    .then(cart => {
      // Check if the free gift feature is enabled
      if (enableFreeGift) {
        // Process cart normally, adding or removing gift as needed
        processCart(cart);
      } else {
        // If feature is disabled, ensure free gift is removed if present
        removeFreeGiftIfPresent(cart);
      }      
    })
    .catch(error => console.error('Error fetching cart:', error))
    .finally(() => {
      // Reset flag when done
      isGiftProductLogicRunning = false;
    });
}

/**
 * Removes the free gift product from cart if present
 * Used when the feature is disabled or cart total drops below threshold
 * 
 * @param {Object} cart - The current cart object
 */
function removeFreeGiftIfPresent(cart) {
  const freeProductVariantId = "{{ product_variant_id }}";
  
  // Check if free product is in cart
  for (const item of cart.items) {
    if (String(item.variant_id) === String(freeProductVariantId)) {
      // Free gift found - remove it
      fetch('/cart/change.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: freeProductVariantId, quantity: 0 })
      })
      .then(response => {
        if (!response.ok) throw new Error('Failed to remove gift product');
        return response.json();
      })
      .then(data => {
        console.log('Successfully removed free product (feature disabled):', data);
        delayedCartUpdate();
      })
      .catch(error => console.error('Error removing free product:', error));
      break;
    }
  }
}

/**
 * Processes the cart to add or remove the free gift based on cart total
 * 
 * @param {Object} cart - The current cart object
 */
function processCart(cart) {
  let cartContainsFreeProduct = false;
  const freeProductVariantId = "{{ product_variant_id }}";
  const qualifyingCartTotal = {{ threshold }} / 100; // Convert from cents to dollars
  const cartTotal = cart.total_price / 100;

  // Check if free product is already in cart
  for (const item of cart.items) {
    if (String(item.variant_id) === String(freeProductVariantId)) {
      cartContainsFreeProduct = true;
      break;
    }
  }

  // Case 1: Cart meets threshold but free gift isn't in cart yet -> Add it
  if (cartTotal >= qualifyingCartTotal && !cartContainsFreeProduct) {
    fetch('/cart/add.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({ items: [{ id: freeProductVariantId, quantity: 1 }] })
    })
    .then(response => {
      if (!response.ok) throw new Error('Failed to add gift product');
      return response.json();
    })
    .then(data => {
      console.log('Successfully added free product:', data);
      delayedCartUpdate();
    })
    .catch(error => console.error('Error adding free product:', error));
  } 
  // Case 2: Cart below threshold but free gift is in cart -> Remove it
  else if (cartTotal < qualifyingCartTotal && cartContainsFreeProduct) {
    fetch('/cart/change.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ id: freeProductVariantId, quantity: 0 })
    })
    .then(response => {
      if (!response.ok) throw new Error('Failed to remove gift product');
      return response.json();
    })
    .then(data => {
      console.log('Successfully removed free product:', data);
      delayedCartUpdate();
    })
    .catch(error => console.error('Error removing free product:', error));
  }
  // Case 3: No action needed (cart either meets threshold and has gift, or is below threshold and has no gift)
}

/**
 * Forces a cart UI update after changes to ensure all elements reflect the current state
 * Uses a short delay to ensure the Shopify API has processed any changes
 */
function delayedCartUpdate() {
  setTimeout(() => {
    fetch('/cart.js')
      .then(response => {
        if (!response.ok) throw new Error('Failed to fetch cart for UI update');
        return response.json();
      })
      .then(cart => {
        // Try multiple methods to refresh the cart UI for different themes
        
        // Method 1: Custom cart:build event
        document.dispatchEvent(new CustomEvent('cart:build'));
        console.log('Cart UI updated programmatically via cart:build');

        // Method 2: jQuery events (used by many themes)
        if (typeof jQuery !== 'undefined' && typeof jQuery(document.body).trigger === 'function') {
          jQuery(document.body).trigger('cart:refresh');
          jQuery(document.body).trigger('cart:build');
        }

        // Method 3: Theme-specific cart popup update function
        if (typeof window.updateCartPopup === 'function') {
          window.updateCartPopup(cart);
        }

        // Method 4: Theme object cart builder
        if (typeof theme !== 'undefined' && theme.cart && typeof theme.cart.buildCart === 'function') {
          theme.cart.buildCart();
        }
      })
      .catch(error => console.error('Error updating cart UI:', error));
  }, 400); // Wait 400ms for Shopify to process the cart change
}

// Custom event that other scripts can listen for
document.addEventListener('cartUpdated', function(event) {
  console.log('Cart was updated:', event.detail);
});
</script>

 

 

5.1 Specify the Product Variant ID of the Gift Product:

{% assign product_variant_id = 41175859724358 %}

5.2 Set enable_free_gift to true:

{% assign enable_free_gift = true %}

6. Add Redirect to the Original Product:

  • Go back to the free product editing page.

  • In the Redirect to Product field, enter the URL of the original product with the full price.

    (This ensures that the free product cannot be purchased directly but can be added to the cart only as a free gift.)


7. Add Code to Track Cart Value and Manage Free Gift Product:

  • Add the following code to snippets/header-cart-drawer.liquid:
<!-- start free-shipping-alert -->
{%- render 'free-gift' -%}
<!-- end free-shipping-alert -->

 

PS
I am using Expanse theme.

Like it?
Thank me using SOL
HjfwGa9XzUugZxREiHSBSJBKAHiVNtk91aYTsaa4rVAs