Order Collections - Number of Products

Tourist
10 1 0

I have struggled with this one and I thought I finally fixed it but when I added another collection recently realized that my method wasn't working. 

Specifically on my product page, I have a list of Collections the product appears in and a selection of products from the same collection (related products). 

The same product may be in multiple collections. What I would like is to choose the collection with the smallest number of products. Less importantly I'd also like for the list of collections the product appears in to start with the smallest collection. 

Think of it like this, an article of clothing - socks - is in a socks category, an undergarments category and a clothing category. I'd rather show the related products from the smallest category which will usually be the most closely related/specific category the way my shop is arranged. 

I was (I  thought) creating an array sorted by number of products in the collection and then using that sorted array to pick my products and list the collections. I haven't figured out what it's really doing. Newest collection (created) or maybe newest collection the product was added to? At any rate, it's not doing it as I hoped. This was the array code for what it's worth. 

{%- assign sorted_collections = product.collections | sort: 'collection.all_products_count' -%}

 

I was then using that sorted_collections array in two other places in my code. Here for the collection list which I wanted to be in order from smallest number of products to largest.

        {% for collection in sorted_collections %}
          <a href="{{ collection.url }}">{{ collection.title }}</a>
          {% endunless %}
        {% endfor %}   


I'll skip the related products code as it's rather lengthy. It's more or less the same as what Shopify gives as example code. I just changed the Forloop to use the same sorted collection array.  

My code did seem to change what collection was picked first from both places but it did not reliably pick the smallest collection. Nor did it seem to be in any discernible order when looking at the number of products in the collections. 

I know a little about coding but by no means am I a programmer. I can usually get by with the right examples to work from but don't assume I know too much. 

Thanks in advance for any push in the right direction (if it's possible at all). 

0 Likes
Highlighted
Tourist
10 1 0

Can anyone tell me if this is even possible - i.e. to sort collections by how many products they have so that smaller collections are displayed first in the collection list? If I at least know it's possible with Liquid, maybe I can figure it out on my own but so far every thing I've tried failed so I'm beginning to think it's not possible. 

Thanks,

Mark

0 Likes