Filter by tag in autocomplete?

Hello,
I need to customize Algolia for Shopify.

Is it possible to alter the autocomplete JS code to send a query filtering by “tag”? Or any other way to do it? I need to filter product search by tag in various regions of the website.

Any code examples, please?

Thank you!

In the file assets/algolia_autocomplete.js.liquid, you have this code:

    return {
      name: section,
      source: $.fn.autocomplete.sources.hits(params.index, {
        hitsPerPage: params.hitsPerPage,
        highlightPreTag: '<span class="aa-highlight">',
        highlightPostTag: '</span>'
      }),
      displayKey: 'title',
      templates: templates
    }

The object used in the source attribute can accept any Algolia parameters, including filters.

First, tags need to be in Algolia’s attributesForFaceting. This means that it needs to be enabled in the Facets list in the Search options tab of the app (if you don’t want them displayed in your search page, you can simply set them with the hidden display type).
Also, you’ll likely only want to apply this tag filtering to products, so you’ll have to use a conditional.

In the end, this would look something like this:

    var srcParams = {
      hitsPerPage: params.hitsPerPage,
      highlightPreTag: '<span class="aa-highlight">',
      highlightPostTag: '</span>'
    };

    if (section === 'products') {
      srcParams.filters = 'tags:"My tag"';
    }

    return {
      name: section,
      source: $.fn.autocomplete.sources.hits(params.index, srcParams),
      displayKey: 'title',
      templates: templates
    }

You can use some custom logic to change the tag depending on the URL too.

1 Like

Thank you!
Great explanation!

With pleasure! Please don’t hesitate to come back if you have issues. :slight_smile:

@Jerska, now, in the results page, I’ve activated instant search. But how do I keep the filters from autocomplete in that page?

It’s filtering the results in autocomplete, but not in the search page.

I’ve tried adding

filters: 'tags: "My Tag"',

in the var instant object, but no luck.

Thanks in advance!

As a follow-up to this question, I’d now recommend you to look at this post which aggregates information from here and other topics: