Possible to get count of available variants?

iamkeir
Shopify Partner
194 0 29
Hi there, I'm desperately trying to find out if there is an equivalent to product.variants.size (which returns all variants, regardless of availability) which will return the total number of _available_ variants only. Obviously product.variants.available.size and product.variants.size.available do not work as available returns true or false and size returns a count, not an array. Any ideas how this can be done? Desperate!
http://iamkeir.com
0 Likes
iamkeir
Shopify Partner
194 0 29

Heh. I figured it out but it ain’t pretty!

{% assign multipleAvailable = 0 %}

{% for variant in product.variants %}

    {% if variant.available %}

        {% if multipleAvailable == 0 %}

            {% assign multipleAvailable = 1 %}

        {% else %}

            {% assign multipleAvailable = 2 %}

        {% endif %}

    {% endif %}

{% endfor %}

Basically I set a flag (multipleAvailable) to 0. Then I enter the variant loop. If a variant is available and it is the first time a variant has been detected as available, it sets the flag to 1. Then if it encounters any subsequent available variants, it sets the flag to 2.

Therefore, if the flag = 1 there is only 1 available variant, if flag = 2 then there are 2 or more available variants.

It’s not a ‘count’ but it’s enough for what I needed.

Yuk yuk yuk. Hope you can suggest something better Shopify!

http://iamkeir.com
bchesler
Tourist
3 0 0

I'm not sure what your use case was here, but this resolved my issue:

 

https://community.shopify.com/c/Shopify-Design/See-if-a-product-has-variants/td-p/414668

0 Likes