Jump to content

Recommended Posts

Hi, I am trying to add a script to my footer, I basically need to give the third item added to cart for free. Can someone correct it for me?

<script>
// Define the product category slugs for the items that need to be purchased for the promotion
const categorySlugs = ['/wuka', '/midi-brief', '/hipster', '/bikini', '/high-waist', '/swim-bikini-brief'];

// Define the number of items that need to be purchased for the promotion
const numItems = 2;

// Define the promo code that needs to be applied for the promotion to be active
const promoCode = 'FREEPANTS';

// Get the cart object
const cart = Squarespace.AjaxCart;

// Listen for the 'cart-variant-added' event
document.addEventListener('cart-variant-added', function (event) {
    // Get the product ID of the added item
    const addedProductId = event.detail.variant.id;

    // Check if the added item is in one of the categories we want to promote
    const addedProductCategory = event.detail.variant.product.category.slug;
    if (categorySlugs.includes(addedProductCategory)) {
        // Check if the promo code is applied
        const appliedPromoCode = cart.getAppliedPromotionCodes()[0]; // Assumes only one promo code is applied
        if (appliedPromoCode === promoCode) {
            // Count the number of items in the cart from the categories we want to promote
            const cartItems = cart.getItems();
            const itemsToPromote = [];
            categorySlugs.forEach(function(slug) {
                let numItemsInCart = 0;
                cartItems.forEach(function(item) {
                    if (item.product.category.slug === slug) {
                        numItemsInCart += item.quantity;
                        itemsToPromote.push(item);
                    }
                });
                
                // Check if we have enough items in the cart for the promotion
                if (numItemsInCart >= numItems) {
                    // Find the third item from the category we want to promote
                    const freeProductIndex = numItemsInCart - 1;
                    const freeProduct = itemsToPromote[freeProductIndex];
                    
                    // Add the free item to the cart
                    cart.addItem(freeProduct.variant.id, 1, {price: 0});
                }
            });
        }
    }
});
</script>
 

Link to comment
  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Popular Days

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.