Shopify themes, liquid, logos, and UX
Return management just got easier! We’ve launched Customer Self-Serve Returns to all Shopify merchants. Click here to learn more!
I'm trying to add a count of the number of available colors for an item on the listing on the collection page. I have looked at many different articles and threads to build my code. Based on the articles I've read my code should work, but it only outputs the total count of all variants (size/color) plus 1. Here's my code:
{% assign value = 0 %} {% if product.available %} {% for product_option in product.options_with_values %} {% if product_option.name == 'Sizes' or product_option.name == 'sizes' or product_option.name == 'size' or product_option.name == 'Size' %} {% for value in product_option.values %} {% assign value = value | plus: 1 %} {% endfor %} {% endif %} {% endfor %} {% endif %} {% if value > 0 %}<small>Colors available - {{ value }}</small>{% endif %}
Hi,
You don't need to loop and count the number of options. The Liquid template language has a filter called size that counts the number of items.
This is how I use on my shop:
{% if product.available %}
{% for product_option in product.options_with_values %}
{% if product_option.name == 'Color' or product_option.name == '色' %}
<div class="h5">
Available colours: {{ product_option.values | size }}
</div>
{% endif %}
{% endfor %}
{% endif %}
(I have a multilingual shop hence the '色' option value).
Here is an alternative way to get the count:
product.options_by_name['Color'].values.size
User | RANK |
---|---|
133 | |
92 | |
77 | |
71 | |
40 |
Learn these 5 things I had to learn the hard way with starting and running my own business
By Kitana Jan 27, 2023Would you love to unleash the unbridled power of the Google Shopping Channel into your sho...
By Gabe Jan 6, 2023How can you turn a hobby into a career? That’s what Emmanuel did while working as a wa...
By Skye Dec 30, 2022