Filter a collections products based on the title with liquid

Highlighted
New Member
3 0 0

Is it possible to assign and filter the current collection on a where or filter for the product titles? I'm not sure of the markup required ie,

{% assign product_collection = collection %}

{% for related_product in product_collection.products limit: product_limit !!can I filter here with a where?!! %}

I would like to filter similar to an SQL LIKE '%keywords%' so finding products which contain a certain similar keyword in the title

0 Likes
Highlighted
Explorer
45 11 11

@shhopify,

 

Sadly, there are a few obstacles in the way of what you want to achieve here.

Liquid does allow you to filter an existing array with the array filter, where. However, where only lets you check for equality (e.g. where 'title' == 'tag'). You can't use expressions (e.g. where 'title' contains 'tag').

As you're unable to filter the actual array, you could skip outputting certain products within the {% for product in collection.products %} loop with if/elsif statements (e.g. {% if product.title contains 'tag' %}). However, as one collection.liquid file is used to render every collection of the store, filtering a few collections by a few tags will mean writing loads of if/elsif statements to try and account for every possibility.

Even if you were to take the if/elsif approach, your collections would only be able to support up to 50 products (a limitation of for loops within Shopify). Any collections with over 50 products are paginated using the paginate tag, which must accept the same array that is iterated over. As you're unable to create this array, there would be inconsistencies in the paginate tag's behaviour if you were to use if/elsif statements.

 

Bad news aside, I noticed in one of your other posts you are tagging products with key:value pairs like colour:blue. Thankfully, Shopify supports filtering collections with product tags by appending the tag name onto the collection URL (e.g. if you wanted to filter a collection called Shirts by products tagged colour:blue you would use this URL: store.myshopify.com/collections/shirts/colour:blue).

More info: https://shopify.dev/tutorials/customize-theme-filter-collections-with-product-tags

 

If that solution isn't appropriate, you could try looking for a third-party app that achieves what you're after.

 

I hope this helps.

Was your problem solved? Please mark this post as an Accepted Solution
0 Likes