How to add multiple products to Shopify cart with one click?

Preface

I recently wrote a configurator in Shopify and decided to share how to add multiple products to a Shopify cart. I didn’t find much material on this issue, especially in Russian.

I am attaching a screencast of what can be done with this. But there are quite a lot of applications, not just the configurator. In the screencast I added 6 products with one click on the “Add to cart” button. But I haven’t reached the limit on the number of added products, maybe there aren’t any.

Cart API

To add multiple items to your cart, you need to send to Cart API an object items with the product identifier (id) and quantity (quantities) of the product. In the screenshot below I am adding one product on click.

Preparing the items object for the API

Preparing the items object for the API

But be sure to send the Product ID instead of the Variant ID if your product has variants, otherwise there will be an error.

This is what the sent object should look like:

items: [ 
 { 
  id: 36110175633573, 
    quantity: 2 
  } 
]

An example of how you can make a fetch request. This is not the most complex version of such a request, but it is not the simplest either.

document.querySelectorAll("form.configurator-form").forEach((form) => {
    form.addEventListener("submit", async (e) => {
      e.preventDefault();

      // Показываем спиннер загрузки
      const loadingOverlays = document.querySelectorAll(".loading-overlay");
      loadingOverlays.forEach((overlay) => overlay.classList.remove("hidden"));

      // Собираем данные товаров
      const productData = selectedProducts.map((product) => ({
        id: product.id,
        quantity: 1,
        variantId:
          product.variantId && product.variantId !== product.id
            ? parseInt(product.variantId)
            : undefined,
      }));

      const requestBody = {
        items: productData,
      };

      // Добавляем товары в корзину
      await fetch(`${window.Shopify.routes.root}cart/add.js`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestBody),
      });

      // Обновляем корзину
      const res = await fetch("/cart.json");
      const cart = await res.json();

      // Обновляем число на корзине
      document.querySelectorAll(".cart-count-bubble").forEach((el) => {
        el.textContent = cart.item_count;
      });

      // Перенаправляем пользователя на страницу корзины
      window.location.href = "https://habr.com/cart";
    });
  });

Conclusion

Be careful when you are faced with this task, there are quite a few pitfalls. For example, if a product has no variants, then ID V value you need to pass it like this:

{{ product.selected_or_first_available_variant.id }}

The full code of the transmitted input will look like this:

 <input class="visually-hidden" type="radio" name="product" value={{ product.selected_or_first_available_variant.id }}>

But if there are options, then this is it:

{{ product.id }}

The complete code is similar to the previous one inputJust value other:

 <input class="visually-hidden" type="radio" name="product" value={{ product.id }}">

Here’s a little trick that you now know. And now you can add multiple items to your cart. Happy development!

Similar Posts

Leave a Reply

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