Add to cart in autocomplete on Shopify

Hi,

How would I go about adding an add to cart button in the autocomplete results next to the products?

Thanks,
Rob

Hi Rob! You could definitely inspire yourself from the logic used for the instantsearch page.

The button is added in the HTML in algolia_instant_search_hogan.liquid:

    [[^ _distinct ]]
      <form id="algolia-add-to-cart-[[ objectID ]]" style="display: none;" action="/cart/add" method="post" enctype="multipart/form-data">
        <input type="hidden" name="id" value="[[ objectID ]]" />
      </form>
      <p class="ais-hit--cart">
        [[# can_order ]]
          <span class="ais-hit--cart-button" data-form-id="algolia-add-to-cart-[[ objectID ]]">
            [[ translations.addToCart ]]
          </span>
        [[/ can_order ]]
        [[^ can_order ]]
          <span class="ais-hit--cart-button ais-hit--cart-button__disabled">
            Out of stock
          </span>
        [[/ can_order ]]
      </p>
    [[/ _distinct ]]

You’ll need to add the same kind of HTML block in algolia_autocomplete_product.hogan.liquid.

This makes use of two variables, _distinct and can_order.
Those are defined in algolia_instant_search.js.liquid:

          item: function (product) {
            product._distinct = instant.distinct;
            product.can_order = (
              product.inventory_management !== 'shopify' ||
              product.inventory_policy === 'continue' ||
              product.inventory_quantity > 0
            );
            product.translations = algolia.translations;
            return product;
          },

The logic is similar for the autocomplete, in algolia_autocomplete.js.liquid.
_distinct is also defined for the autocomplete, but not can_order, that you’ll need to add in :

      suggestion: function displaySuggestion (hit) {
        return algolia.render(params.templates.hit, Object.assign({ _distinct: params.distinct }, hit, {translations: algolia.translations}));
      }

Something like this should work:

      suggestion: function displaySuggestion (hit) {
        return algolia.render(params.templates.hit, Object.assign(
          { _distinct: params.distinct },
          hit,
          { can_order: (
            product.inventory_management !== 'shopify' ||
            product.inventory_policy === 'continue' ||
            product.inventory_quantity > 0
          )},
          { translations: algolia.translations }));
      }