Skip to content

Instantly share code, notes, and snippets.

@enamhasan
Created October 21, 2023 02:05
Show Gist options
  • Save enamhasan/de39c2a078fe47735996e9c0ccc77e48 to your computer and use it in GitHub Desktop.
Save enamhasan/de39c2a078fe47735996e9c0ccc77e48 to your computer and use it in GitHub Desktop.
Shopify Select First Variant On Stock When Product Page Loads
{%- comment -%}
If the product first varaiant inventory is 0 then find the variant with inventory and load the product page
{%- endcomment -%}
{%- assign current_variant = product.selected_or_first_available_variant -%}
{%- assign availableVariantId = '' -%}
{%- assign availableVariantFound = false -%}
{%- if current_variant.inventory_quantity <= 0 -%}
{%- for variant in product.variants -%}
{%- if variant.inventory_quantity > 0 and availableVariantId == '' -%}
{%- assign availableVariantId = variant.id -%}
{%- assign availableVariantFound = true -%}
{% break %}
{%- endif -%}
{%- endfor -%}
{% endif %}
{% if availableVariantFound %}
<script>
window.location.href = '/products/{{ product.handle }}?variant={{ availableVariantId }}';
</script>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment