Tag count automatically changing while clicking on the product tag

核能气质少年 提交于 2019-12-02 04:21:32

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" 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.

As I was saying in comment, the issue comes from your secondary loop:

{% for product in collection.products %}

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:

{% assign whole_collection = collections[collection.handle] %}
{% for product in whole_collection.products %}
 {% if product.tags contains tag %}
 {% assign products_count = products_count | plus: 1 %}
 {% endif %}
{% endfor %}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!