I am using Shopify. I am in collection page where I am getting all the filter with tag count something like,
All Products
Apple(4)
Banana(2)
Orange(1)
Mango(8)
Now when I click on any of the tag(For example I clicked on Banana) then It will display the banana products.
Now my issue is by clicking on the tag it’s changing the tag count.
All Products
Apple(0)
Banana(2)
Orange(0)
Mango(4)
I am using below code
{% for tag in collection.all_tags %}
{% assign products_count = 0 %}
{% for product in collection.products %}
{% if product.tags contains tag %}
{% assign products_count = products_count | plus: 1 %}
{% endif %}
{% endfor %}
<a class="filter__link" href="/collections/{% if collection.handle != blank %}{{ collection.handle }}{% else %}all{% endif %}/{{ tag | handleize }}"{% if current_tags contains tag %} selected="selected" id="tag_active"{% endif %}>{{ tag }} ({{products_count }})</a>
{% endfor %}
Thanks in advance.
2
Answers
As I was saying in comment, the issue comes from your secondary loop:
Which accesses only to the current view and not the full collection products.
I’ve not tested it but I guess it worthes a try:
Explanation, a code like this {{ collections[‘the-handle’].url }} allows access to any specific collection and its attributes.
HTH
Memo : this won’t work accurately if your collection has more than 50 items.
It looks like the step you’re missing is the first line here:
You’re iterating over the current collection, so as you’ve noticed when you click on a tag the results change.
If you don’t have a collection with the handle
all
, you can create one by following this process:All
.Edit:
This fixes the issue where the product count changes when you click on a tag link:
The key part is:
It looks like when you’re filtering by tag with a URL like
collections/collection_1/tag_1
thencollection.products
is also filtered by the selected tag. The line above looks a bit messy, but it appears to return the full set of products.