Ad

Tag Count Automatically Changing While Clicking On The Product Tag

- 1 answer

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" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" 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.

Ad

Answer

It looks like the step you're missing is the first line here:

{% assign collection = collections.all %}

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:

  1. Go to Products > Collections.
  2. Click Add a collection.
  3. Create the collection:
    1. Give your collection the Title All.
    2. In the Conditions section, select "Automatically select products based on conditions".
    3. Set the product condition "Product price is greater than $0".
  4. Save

Edit:

This fixes the issue where the product count changes when you click on a tag link:

{% for tag in collection.all_tags %}
    {% assign products_count = 0 %}
    {% for product in collections[collection.handle].products %}
        {% if product.tags contains tag %}
            {% assign products_count = products_count | plus: 1 %}
        {% endif %}
    {% endfor %}
    <a class="filter__link" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" 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 %}

The key part is:

{% for product in collections[collection.handle].products %}

It looks like when you're filtering by tag with a URL like collections/collection_1/tag_1 then collection.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.

Ad
source: stackoverflow.com
Ad