I searched far and wide and saw a bunch of posts with code to show inventory quantity on the product page but none of them worked properly on products that had variants. It would only show the inventory quantity for the default variant that was selected when the page loads. If you changed the variant, the quantity would not update.
The following is the code I use that works. I'm using Simple theme but this will work with Debut and many other themes.
{% comment %} Inventory tracking on product page {% endcomment %}
{% for variant in product.variants %}
<div InventoryManagment data-id="{{variant.id}}" data-inventory="{{variant.inventory_quantity}}" style="display:none;"></div>
{% endfor %}
<div id="variant-inventory" class="{% unless current_variant.available %} hide {% endunless %}">
{% if current_variant.inventory_management == "shopify" and current_variant.inventory_policy != "continue" %}
We have <b>{{ current_variant.inventory_quantity }}</b> in stock.
{% else %}
{% endif %}
</div>
{% comment %} END inventory tracking on product page {% endcomment %}
if (variant) {
let inventoryHash = document.querySelectorAll('[inventorymanagment]');
debugger;
Array.from(inventoryHash).forEach(
(Selectedvariant)=>{
if(Selectedvariant.dataset.id == variant.id){
if(Selectedvariant.dataset.inventory < 10)
{
$("#variant-inventory").html("Only <b>"+ Selectedvariant.dataset.inventory +"</b> left in stock. <p>");
}
else{
$("#variant-inventory").html("<p>");
}
}
}
);
And that's it. It should work now. Shout out to @tim for being a great resource in this forum and answering so many questions. While he didn't directly answer questions for me, his past posts helped me make sense of it all.
User | Count |
---|---|
23 | |
23 | |
13 | |
13 | |
11 |