Product Badges - Limited Stock - based on all variant inventory
This script will show a badge for Limited Stock if all the variants are 3 or less.
Change {% if total < 4 %} to the number being checked.
How it works:
- Checks to see if inventory is managed by shopify
- Checks to see if there are product variants
- Loops and captures an array of all the variant inventory
- Loops and captures true or false statements for each variant checking to see if it is 3 and below
- Creates another array for true and false statements
- If the second array contains false then badge won't show
- For badge to show all true needs to return aka all inventory 3 and below
- Else if product doesn't have variants just checks to see if inventory is 3 and below
{% if product.variants.first.inventory_management == "shopify" %}
{% if product.variants.size > 1 %}
{% capture i %}
{%for variant in product.variants %}
{% if forloop.first == true %}[{% endif%}
{{ variant.inventory_quantity }}
{% if forloop.last == false %},{% endif%}
{% if forloop.last == true %}]{% endif%}
{%endfor%}
{%endcapture%}
{% assign inv = i | split: ',' %}
{% capture ii %}
{% for invNum in inv %}
{% assign total = invNum | plus: 0 %}
{% if forloop.first == true %}[{% endif%}
{% if total < 4 %}
true
{% else %}
false
{% endif %}
{% if forloop.last == false %},{% endif%}
{% if forloop.last == true %}]{% endif%}
{%endfor%}
{%endcapture%}
{% if ii contains "false" %}
{% else %}
<label class="labels label-limited">Limited Stock</label>
{% endif %}
{% else %}
{% if product.variants.first.inventory_quantity < 4 %}
<label class="labels label-limited">Limited Stock</label>
{% endif %}
{% endif %}
{% endif %}