Can anyone help me finish my code here? I’m trying to filter search results by only showing products tagged with a tag that matches customer tags.
For example, a customer (tagged with “Mustang”) searches Ford on the front end. (Normally - all Ford products would be displayed.) However, If the customer is tagged Mustang, only products tagged Mustang would display.
Here’s what I have so far; the results aren’t empty, but they do not display.
{% for item in search.results %}
{% if item.object_type == 'product' %}
{% for tag in product.tags %}
{% if tag contains customer.tags %}
{% assign product = item %}
{% include 'product-grid-item' %}
{% endif %}
{% endfor %}
{% else %}
## {{ item.title | link_to: item.url }}
{{ item.content | strip_html | truncatewords: 50 }}
{% endif %}
{% endfor %}
Do the opposite of what you’re checking for tags, you want to see if customer.tags contains tag:
{% if customer.tags contains tag %}
{% assign product = item %}
{% include 'product-grid-item' %}
{% endif %}
You’ll have problems with this depending on how much you’re paginating by and because of the 50 forloop limit. Say you are paginating by 20 products. When the customer searches for Ford, and in the first 100 products returned for Ford only 10 are tagged Mustang. 1 product between 0 - 10, 1 between 11 - 20, 1 between 21 - 30, etc. – If you’re paginating by 20, it’s only going to show 2 products on the first page and make you navigate to the next page to see the next products, it isnt going to return all the products and put them on that first search result page because it’s still cycling through 20 products, but it’s only coming back with 2 between those first 20. The pagination doesnt know that you only output 2 items from the 20 iterations you went through, it assumes there has been an item output for every iteration of the loop.
Also, if you don’t paginate at all, there’s a 50 iteration limit for forloops. So it’s only going to cycle through the first 50 search results and if the first product from a search of Ford that has the tag Mustang is product 51 or higher, it’ll never get returned. You can hack this by paginating and doing it by 1000, I believe that’s the limit for pagination. But if you have more than 1000 products that’s not much help. Anyway, I don’t know your particular situation. See if the above code works for you, but you may have to pass product to product-grid-item: