Limit cart quantities to in-stock items

Tip

This article is only relevant to you if your Shopify theme brings your customers to the cart page when an item is added to the cart. It will be helpful if you use the New Standard, Minimal or React theme, for example.

The problem

On the product page, Shopify shows an item as still available when all of its inventory has been added to the cart. Adding more of the item to the cart with a regular POST request — not Ajax — will not produce an error, and the requested quantity will be added to the cart. At checkout, the shopper will be informed of necessary quantity adjustments. You may not want for them to wait that long to discover that the item they want is low in stock.

The fix

  1. From your Shopify admin, click Online Store, and then click Themes (or press G W T).

  2. Find the theme you want to edit, click the ... button, and then click Edit HTML/CSS.

  3. On the left, under Templates, click product.liquid to open your product template in the code editor.

  4. At the very bottom of your product.liquid file, add the following:

    
    {% if template contains 'product' and product.available %}
    <script>
    jQuery('form[action="/cart/add"]').submit(function(e) {
      e.preventDefault();
      jQuery.ajax( {
        url: '/cart/add.js',
        type: 'post',
        dataType: 'json',
        data: jQuery(this).serialize(),
        success: function() { window.location.href = '/cart' },
        error: function(jqXHR) {
          var response = eval('(' + jqXHR.responseText + ')').description;
          if (response.slice(0,4) === 'All ') {
            jQuery('form[action="/cart/add"]').find('input[type="submit"], button[type="submit"]').val('Sold Out').addClass('disabled').attr('disabled','disabled');
            alert(response.replace('All 1 ', 'All '));
          }
          else {
            alert(response);
          }
        }
      } );
    });
    </script>
    {% endif %}
    
    

Want to discuss this page?

Visit the Shopify Community