How to set the default availability as in-stock for Search & Discovery?

How it works

As Search & Discovery doesn’t support setting default filter values, we can only modify the collections link through JavaScript.

Javascript code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<script>
class LinkModifier {
constructor(blockedKeywords, defaultFilterOptions) {
this.blockedKeywords = blockedKeywords;
this.defaultFilterOptions = defaultFilterOptions.join('&');
}

modifyLinks() {
// Find all <a> tags with an href attribute that contains "collections" but does not contain "products"
const links = document.querySelectorAll('a[href*="collections"]:not([href*="products"])');

// Modify the href attribute of all matching <a> tags by adding the default filter options to the end of the URL
// If the URL already contains a query string, add "&" to the end; otherwise, add "?"
for (let i = 0; i < links.length; i++) {
let href = links[i].getAttribute('href');

// Check if the current URL contains any of the blocked keywords, and skip if it does
if (this.blockedKeywords.some(keyword => href.includes(keyword))) {
continue;
}

let separator = href.indexOf('?') !== -1 ? '&' : '?';
href += separator + this.defaultFilterOptions;
links[i].setAttribute('href', href);
}
}
}

// Create an instance of the LinkModifier class with an array of blocked keywords and default filter options
const linkModifier = new LinkModifier(['blocked', 'keywords', 'go', 'here'], ['filter.v.availability=1', 'filter.v.color=red']);

// Wait for the page to finish loading, then execute the modifyLinks method of the LinkModifier instance
window.addEventListener('load', () => {
linkModifier.modifyLinks();
});
</script>


How to use

  • Online store > themes > Actions > Edit code > theme.liquid
  • Copy the code above and paste it before the </body> tag.
  • Find this piece of code.
1
const linkModifier = new LinkModifier(['blocked', 'keywords', 'go', 'here'], ['filter.v.availability=1', 'filter.v.color=red']);

If we want some pages to not have default filter options, we can add those collection handles in the first parameter. If not, keep the array empty [].

The second parameter is for the parameters that you wish to set as defaults, with the format of filter name=filter value.