Help with checking product availability

Solved
mfrench
New Member
2 1 0

Hey all, long time reader, first time poster.

I've created a little snippet to show the customer if a variant is unavailable over the selector button, so they don't have to select the option to see if it's in stock or not.

The code I've got seemed to be working exactly as intended, but it turns out there's just a few products that show incorrect items out of stock. And I can't find any issue in the actual product settings, so I assume there's some error in my snippet:

{%- for value in option.values -%}
  {%- unless product.variants[forloop.index0].available -%}
    {%- assign opt_sold_out = true -%}
  {%- endunless -%}

  <label class="{%- if opt_sold_out -%}opt-sold-out{%endif%}">XS etc...</label> (then apply the custom class to style the button to look out of stock with)

{%- endfor -%}

I feel like I may be missing something obvious... Any suggestions what may be causing the issue?

0 Likes
mfrench
New Member
2 1 0

This is an accepted solution.

Yes I was missing something obvious... For anyone having a similar issue, the issue was that as soon as the forloop hit an out of stock item the variable always evaluated to true.

Swapped the unless statement to an if/else statement to re-test and reset the variable on each iteration. Works like a charm now.

 

{%- for value in option.values -%}
  {%- if product.variants[forloop.index0].available -%}
    {%- assign opt_sold = false -%}
  {%- else -%}
    {%- assign opt_sold = true -%}
  {%- endif -%}
  <label class="{% if opt_sold %}opt-sold-out{% endif %}">The option name</label>
{%- endfor -%}

 

DOH

0 Likes
c10s
Shopify Partner
15 2 3

It tough to say exactly without seeing more of the code but I suspect the issue is because an option doesn't necessarily equal a variant, as a variant can have multiple options (eg. colour + size). It's the combination of those options that creates a variant, which is available or not.

This is the simplest form that will work regardless of the number of options:

{% for variant in product.variants %}
    <label class="{%- if variant.available == false -%}opt-sold-out{%- endif -%}">{{ variant.title }}</label>
{% endfor %}

 If you want separate options (eg. colour and size are separate inputs or button groups) you'll need some JavaScript to look at what's currently selected and what potential combinations are, then mark the option available or not.

0 Likes