We were working on a WooCommerce project that required us to add multiple products to the cart from a single click of a button.
We wanted a solution from the JavaScript side, and we came up with the following code. This should fire when the “add to cart” button is clicked:
const productsToAdd = [
{ 'add-to-cart': 68, 'quantity': 2 }, // 68 is Product ID
{ 'add-to-cart': 69, 'quantity': 3 },
{ 'add-to-cart': 70, 'quantity': 4 }
];
for (const product of productsToAdd) {
try {
const response = await fetch(window.location.pathname, {
method: 'POST',
body: new URLSearchParams(product),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
if (response.ok) {
console.log('Product added to cart:', product['add-to-cart']);
}
} catch (e) {
console.error(e);
}
};
Here’s a gist that contains the solution.
Leave a Reply