Show The Number of Products Left in Stock on Shopify
Step 1: Duplicate your live theme
- From your Shopify admin go to Online store and choose themes.
- Next to the live theme click on Actions and choose Duplicate.
- This way you will have a backup of your live theme in case you miss some step and mess up your store.
Step 2: Edit Product-Template.liquid
- Now that you have the duplicate of your theme you can click on Actions again, but this time choose Edit Code.
- From the navigation to the left go to Sections directory and choose Product-template.liquid.
- Find the place you want to show your message, maybe above add to cart button, and paste the following code:
{% comment %} Inventory tracking on product page {% endcomment %}
<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 {{ current_variant.inventory_quantity }} in stock.
{% else %}
This product is available.
{% endif %}
</div>
In case you don’t have multiple variants you can Click on Save and the message of quantity should be visible on your Site.
Step 3: Edit Product-Template.liquid
- In case you have multiple variants you will need to add one additional line in the product-template.liquid.
- Paste the following code right above the code you just pasted in the product-template.liquid and click on Save.
{% for variant in product.variants %}
<div InventoryManagment data-id=”{{variant.id}}” data-inventory=”{{variant.inventory_quantity}}” style=”display:none;”></div>
{% endfor %}
Step 4: Edit Theme.js
- From the navigation to the left scroll down to the assets directory and choose theme.js.
- In this new js file search for the “variantchange”. It’s important to place the following code inside the variantchange block.
- In our case, we are using the Debut theme, it should be on the line 748.
let inventoryHash = document.querySelectorAll(‘[inventorymanagment]’);
debugger;
Under that piece of code paste the following
Array.from(inventoryHash).forEach(
(Selectedvariant)=>{
if(Selectedvariant.dataset.id == variant.id){
if(Selectedvariant.dataset.inventory > 0)
{
$(“#variant-inventory”).html(“We have “+ Selectedvariant.dataset.inventory +” in stock”);
}
else{
$(“#variant-inventory”).html(“Sold out!”);
}
}
}
);
Click on Save and your message of quantity should be visible and working on your site.