All guides › Add a second product with one button

Add another product to the cart from a Shopify product page, with one button

Disclosure: I build No-App Sections; this guide was written with AI assistance. The code on this page was written for this guide. It passes Shopify's Theme Check inside Dawn 16.0.0 and automated tests in headless Chrome, run against Dawn's own cart and variant events with mocked store data. It hasn't been run on a live store yet, so try it on a duplicate theme first.

Sometimes the extra isn't a recommendation, it's the same small thing for every product: a gift box, a sample, a care kit, an extended warranty. You want a button under the main Add to cart that adds that product, opens the cart drawer like the main button does, and doesn't take the shopper away from the page. Here's a block that does exactly that.

The idea in one paragraph

Shopify's cart accepts a plain HTML form posted to /cart/add with a variant id and a quantity. That works in every theme, but it reloads to the cart page. Dawn's own Add to cart button posts the same form with fetch, asks Shopify to render the cart drawer in the same response, and hands it to the drawer. The block below does the same when it finds Dawn's cart-drawer or cart-notification, and falls back to the plain form when it doesn't.

Before you start: the add-on product

  • Create it like any product and note its handle, the last part of its URL. For "Gift box" it's usually gift-box.
  • Make sure it's Active and available on the Online Store sales channel. If you track its inventory, keep it in stock, because the button hides itself when the add-on is sold out.
  • To keep it out of search results, add the product metafield seo.hidden (integer, value 1). Shopify uses it to hide a product from storefront search.

The block code

Change 'gift-box' to your handle:

{%- comment -%}
  "Add another product" button for the product page (Dawn "Custom Liquid" block).
  Change 'gift-box' to the handle of the product you want to add (the last part of its URL).
{%- endcomment -%}
{%- liquid
  assign addon = all_products['gift-box']
  assign addon_variant = addon.selected_or_first_available_variant
-%}
{%- if addon != blank and addon.id != product.id and addon_variant.available -%}
  <form
    class="addon"
    id="addon-{{ section.id }}"
    method="post"
    action="{{ routes.cart_add_url }}"
    accept-charset="UTF-8"
  >
    <input type="hidden" name="id" value="{{ addon_variant.id }}">
    <input type="hidden" name="quantity" value="1">
    <button type="submit" class="button button--secondary addon__button">
      Add {{ addon.title | escape }} ({{ addon_variant.price | money }})
    </button>
    <p class="addon__error" role="alert" hidden></p>
  </form>
  <style>
    .addon { margin: 0 0 1.5rem; }
    .addon__button { width: 100%; }
    .addon__error { color: rgb(var(--color-foreground)); font-size: 1.3rem; margin: 0.8rem 0 0; }
  </style>
  <script>
    (function () {
      var form = document.getElementById('addon-{{ section.id }}');
      if (!form) return;
      var button = form.querySelector('button');
      var error = form.querySelector('.addon__error');
      form.addEventListener('submit', function (event) {
        /* Dawn's cart drawer or popup notification. With "Cart type: Page" there is neither, */
        /* so the form simply posts and Shopify opens the cart page. */
        var cart = document.querySelector('cart-drawer') || document.querySelector('cart-notification');
        if (!cart || typeof cart.renderContents !== 'function' || !window.fetch) return;
        event.preventDefault();
        if (button.getAttribute('aria-disabled') === 'true') return;
        button.setAttribute('aria-disabled', 'true');
        error.hidden = true;

        var body = new FormData(form);
        body.append('sections', cart.getSectionsToRender().map(function (s) { return s.id; }));
        body.append('sections_url', window.location.pathname);
        if (cart.setActiveElement) cart.setActiveElement(document.activeElement);

        fetch(window.routes.cart_add_url, {
          method: 'POST',
          headers: { 'X-Requested-With': 'XMLHttpRequest', Accept: 'application/javascript' },
          body: body
        })
          .then(function (r) { return r.json(); })
          .then(function (response) {
            if (response.status) {
              /* Shopify's cart errors, e.g. "All 1 Gift box are in your cart." */
              error.textContent = response.description || response.message || 'Could not add to cart.';
              error.hidden = false;
              return;
            }
            cart.classList.remove('is-empty');
            cart.renderContents(response);
            if (typeof publish === 'function' && typeof PUB_SUB_EVENTS !== 'undefined') {
              publish(PUB_SUB_EVENTS.cartUpdate, { source: 'addon-button', productVariantId: body.get('id'), cartData: response });
            }
          })
          .catch(function () {
            error.textContent = 'Could not add to cart. Please refresh the page and try again.';
            error.hidden = false;
          })
          .finally(function () { button.removeAttribute('aria-disabled'); });
      });
    })();
  </script>
{%- endif -%}

Details worth knowing

  • It hides itself on the add-on's own product page, when the handle is wrong, and when the add-on is sold out.
  • Errors are Shopify's own. If the cart refuses the item (e.g. not enough stock), Shopify answers with a 422 and a description like "All 1 Gift box are in your cart.". The block shows it under the button.
  • Other parts of the page hear about it. After a successful add, it publishes Dawn's cartUpdate event, so a free shipping message or cart counter listening for it updates too.
  • No double adds. While a request is running, a second tap is ignored. If the network fails, it shows an error and doesn't retry by itself, so a slow connection can't add the item twice.
  • all_products has a limit: Shopify allows 20 unique handles per page through it. One add-on is fine. Don't build a 30-product list this way.

Add it to your product page

  1. Duplicate your theme. In Online Store → Themes, duplicate your theme and click Customize on the copy.
  2. Open the product template. Choose Products → Default product from the page selector. To use the button on some products only, create a separate product template for them.
  3. Add a Custom Liquid block. In Product information, click Add block → Custom Liquid and drag it under Buy buttons.
  4. Paste, set the handle, save. Paste the code, change gift-box to your add-on's handle, and click Save.

With "Cart type: Page" or another theme

If Theme settings → Cart → Cart type is Page, Dawn has no drawer or pop-up to update. The script steps aside, the form posts normally, and Shopify adds the item and opens the cart page. That's also what happens in any theme without Dawn's cart elements. The button still works, it just navigates. Style classes button button--secondary are Dawn's. In other themes, swap them for your theme's button classes.

Testing checklist

  1. Cart type Drawer: click the button. The drawer opens with the add-on and the page doesn't navigate.
  2. Cart type Popup notification: the pop-up shows the add-on.
  3. Cart type Page: you land on the cart page with the add-on in it.
  4. Set the add-on's stock to 1 and click twice: the second click shows Shopify's stock message.
  5. Open the add-on's own product page: no button there.

Want several add-ons with images?

The Upsell block shows a "Frequently bought together" row of up to 4 products you pick in the theme editor, each with an image and its own add-to-cart button. Sold-out products are labelled. You set the heading, button text and spacing in the theme editor. It's £12 one-off, for one store, and tested on Dawn and Horizon. Other Online Store 2.0 themes may need small style tweaks.

Buy the upsell block, £12 Try the live demo

FAQ

Can the button add the add-on and the main product together?

This block adds only the add-on. Bundling both in one click changes how Dawn's main form works, so it's left out here.

Can I add a gift message with it?

Yes: add <input type="text" name="properties[Gift message]"> inside the form. Shopify stores it as a line item property, and it shows in the cart and the order.

Why is the add-on's price shown in the button?

So nobody is surprised at checkout. Remove the ({{ addon_variant.price | money }}) part if you prefer.

What if the add-on has several variants?

The block adds its first available variant. For a choice, use a <select name="id"> with one <option> per variant instead of the hidden input.

Do I need the JavaScript at all?

No. Without it, the form still adds the product and opens the cart page. The script only keeps the shopper on the product page in Dawn.