Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
Hi! Im currently working on implementing some tracking pixel with the new Web Pixels API.
When the product_added_to_cart (as well as removed) event is called I need to get the new total cart value.
How can I do this?
Thank you!
Hi,
It can be done by setting up custom event listeners and making requests to the /cart.js endpoint whenever a product is added or removed from the cart.
Use the total_price property from the fetched cart data to get the total value and incorporate it into your tracking pixels as needed.
Define the Event Listener and Fetch Cart Data code example
// Define your pixel script
(() => {
// Listen for `product_added_to_cart` event
Shopify.CustomerEvents.subscribe('product_added_to_cart', async (event) => {
console.log("Product added to cart:", event);
// Fetch cart details
const cart = await getCartDetails();
console.log("Updated Cart Total:", cart.total_price / 100); // Cart total in dollars
});
// Listen for `product_removed_from_cart` event
Shopify.CustomerEvents.subscribe('product_removed_from_cart', async (event) => {
console.log("Product removed from cart:", event);
// Fetch cart details
const cart = await getCartDetails();
console.log("Updated Cart Total:", cart.total_price / 100); // Cart total in dollars
});
// Function to fetch cart details
async function getCartDetails() {
try {
const response = await fetch('/cart.js'); // Shopify's default cart endpoint
const cart = await response.json();
return cart;
} catch (error) {
console.error("Error fetching cart details:", error);
}
}
})();
Starting a B2B store is a big undertaking that requires careful planning and execution. W...
By JasonH Sep 23, 2024By investing 30 minutes of your time, you can unlock the potential for increased sales,...
By Jacqui Sep 11, 2024We appreciate the diverse ways you participate in and engage with the Shopify Communi...
By JasonH Sep 9, 2024