Create a custom link helper for autocomplete links

I have done something like this on the instant search page. I want to do the same on the Autocomplete pages.

How can I do this:

instantsearchLink: function instantsearchLink () {
  var addVariantId = !this._distinct && this.objectID !== this.id;
  if (this.product_type === 'Residential') {
      return '/collections/' + this.handle;
  } else {
     return '/products/' + this.handle + (addVariantId ? ('?variant=' + this.objectID) : '');
  }
}

Is there a way that I’m not seeing to do this in the autocomplete?

Hi @dave2 , I’ve just noticed that this question was unanswered, but didn’t receive a notification for it, I’m really sorry.

There are two ways for us to redirect users to a product page:

  • A link on the product title (as done in the instant search page
  • A JavaScript redirection when clicking on a result

If you go on your instantsearch page, you’ll notice that if you hover over the link, you’ll see the target at the bottom of your browser window, but you can also click elsewhere on the result (e.g. the image) and be redirected.
This second part is the JavaScript redirection I’m mentionning. We have the same in the autocomplete.

In algolia_autocomplete.js, here’s what the code looks like:

    autocomplete.$input.on('autocomplete:selected', function (obj, datum, name) {
      if (name === 'products') {
        var addVariantId = !autocomplete.products.distinct && datum.objectID !== datum.id;
        window.location.href = '/' + name + '/' + datum.handle + (addVariantId ? ('?variant=' + datum.objectID) : '');
      } else if (name === 'articles') {
        window.location.href = '/blogs/' + datum.blog.handle + '/' + datum.handle;
      } else {
        window.location.href = '/' + name + '/' + datum.handle;
      }
    })

Here, datum is the selected object. You can modify this code to do exactly what you want.

In algolia_instant_search.js.liquid , here’s what the code looks like:

    // Redirect to product on click
    instant.search.addWidget({
      init: function (opts) {
        $('.ais-hits-container').on('click', '.ais-hit', function (e) {
          var $this = $(this),
              handle = $this.attr('data-handle'),
              variant_id = $this.attr('data-variant-id')
              distinct = $this.attr('data-distinct');

          var link = '/products/' + handle;
          if (distinct !== 'true') {
            link += '?variant=' + variant_id;
          }
          window.location.href = link;
        });
        $('.ais-hits-container').on('click', '.ais-hit a', function (e) {
          e.stopPropagation();
        });
      }
    });

In this case, you don’t directly have access to the object properties.
You can pass them along, as we do for the id, the handle and distinct, using data attributes defined in algolia_instant_search_product.hogan.liquid.

In both cases, you should be able to modify the code to achieve what you want. :slight_smile: