Introduction
AddToCart events track when users add items to their shopping cart. This guide explains how to implement AddToCart events for both single and multiple item scenarios.
When to Fire AddToCart
Fire AddToCart events when:
- Add to Cart Click: User clicks "Add to Cart" button
- Item Added: Item is successfully added to cart
- Quantity Updated: User increases quantity of item in cart
Fire the event after the item is successfully added to the cart, not before.
Parameter Structure
AddToCart events should include:
- content_ids (required): Array of product IDs added to cart
- content_type (required): Type (typically "product")
- value (optional): Total value of items added
- currency (optional): Currency code (required if value provided)
- contents (optional): Array of item objects with id, quantity, item_price
- num_items (optional): Number of items added
Single Item Example
function addToCart(productId, productName, price) {
const userData = {
country: "US"
};
st('track', 'AddToCart', {
content_ids: [productId],
content_type: 'product',
content_name: productName,
value: price,
currency: 'USD',
num_items: 1
}, userData);
}
Multiple Items Example
function addMultipleToCart(items) {
const contentIds = items.map(item => item.id);
const totalValue = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
const contents = items.map(item => ({
id: item.id,
quantity: item.quantity,
item_price: item.price
}));
const userData = {
country: "US"
};
st('track', 'AddToCart', {
content_ids: contentIds,
content_type: 'product',
value: totalValue,
currency: 'USD',
contents: contents,
num_items: items.reduce((sum, item) => sum + item.quantity, 0)
}, userData);
}
Value Calculation
Calculate value based on:
- Single Item: Item price × quantity
- Multiple Items: Sum of (item price × quantity) for all items
- Current Price: Use the current/actual price at time of adding to cart
Contents Array
For detailed tracking, include contents array:
contents: [
{
id: "product-123", // Product ID (string)
quantity: 2, // Quantity added
item_price: 49.99 // Price per item (not total)
}
]
Best Practices
- Fire After Success: Fire event after item is successfully added to cart
- Include Value: Always include value and currency for better tracking
- Use Contents Array: Include contents array for detailed product information
- Handle Multiple Items: Properly calculate totals for multiple items
Summary
AddToCart events track cart additions. Include content_ids, content_type, value, currency, and optionally contents array. Fire after items are successfully added to cart.