Shopify Tutorial: Limiting Storefront Search to Certain Product Types
In this tutorial, we’re going to be adding a dropdown to a shop’s search bar that will limit search results to certain product types. You can see a demo of this here. As an example, try selecting “kicks” under product type and searching for “gnarly”. Notice that only products with the type “kicks” are returned in the search results!
Let’s get started!
The idea for this article came when I came across this article in the Shopify Wiki, which I actually had no idea about.You can pass special parameters to Shopify’s storefront search and limit the results by page titles, product vendors, product variants, etc. I figured the most practical example would be to search by product type.
Shopify’s storefront search works by checking the value of the input with the name attribute “q”. Within the <form> for the search, you can have a hidden input like this:
<input type="hidden" name="q" value="" />
You can then pass in values from the fields listed here. For example, you can do:
<input id="param" type="hidden" name="q" value="product_type:foo bar" />
…where “foo” is the product type and “bar” is the search query. What we can do then is create a dropdown and populate it with the shop’s product types, and use some jQuery to swap the value of “foo” with the selected product type from the dropdown.
1. Create a dropdown with the shop’s product types
The first step is to create a dropdown that is dynamically populated with all of the shop’s different product types.
Copy this gist and paste it into your theme. Where you paste it depends on which theme you’re using, but it should be placed close to <form&rt; for the search bar. In my demo I added some CSS to position is next to the search bar.
2. Add the script for generating the search query
Copy the contents of this gist and place it right before the closing </body> tag, at the bottom of theme.liquid.
This simple script checks the value of the selected option in the product types dropdown and adds it to the query of the search.
That’s it that’s all! I wanted to also set up a demo where you have a checkbox for each product type, and search within multiple product types, but it doesn’t look like you can do that Ex: the search below does not work.
product_type:foo or product_type:bar