Add Multiple Products to WooCommerce Cart using the fetch API


Add Multiple Products to WooCommerce Cart using the fetch API

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
    { '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.

However, if you are looking for a solution that modifies the WooCommerce functionality to allow for multiple products to be added, you might prefer this solution:

Either way, this should help you add multiple products to the WooCommerce cart in one click. Hope that helps!

Leave a Reply

Your email address will not be published. Required fields are marked *