Get Variant ID of First Variant that Matches Option

New Member
2 0 0

(Just realized I ought to have posted this in the Shopify Design Forum)


I'm working on a store that routinely has products with both color and size options. I'm trying to implement color swatches for product cards in collection views, and I'd like the swatches to link to the variant ID of the first variant that matches the color. (e.g. show swatches for the red, blue, and green colors, and have each of those link to the first variant that matches the color, - likely resulting in linking to the variant for red/small, blue/small, green/small respectively.)


I've found decent documentation on listing the values of option1 and option2, but I can't seem to find anything explaining how I might do something along the lines of "give me the first variant id that matches 'option1 = red'"


Appreciate any help or insight anyone is able to provide! 

Shopify Expert
2529 423 535

Hi @aeblin 

Use this code may be work:

{% for option in product.options %}
	{% assign opt = option | downcase %}
	{% assign option_index = forloop.index0 %}
	{% if opt == 'color' or opt == 'colour' %}
		{% assign values = '' %}
			{% for variant in product.variants %}
				{% assign value = variant.options[option_index] %}

				{% unless values contains value %}
			      	{% assign values = values | join: ',' %}
			      	{% assign values = values | append: ',' | append: value %} 
			      	{% assign values = values | split: ',' %}
			      		<label for="variant-{{ }}">{{ value }}</label>
			      		<input type="radio" name="id" value="{{ }}" id="variant-{{ }}">
			    {% endunless %}
			{% endfor %}
	{% endif %}
{% endfor %}
Want to modify or custom changes on store hire me.
If helpful then please Like and Accept Solution.
Skype: jasoliya.brijesh
Want to get Free review and advice for sale on store ?? just text me here