Skip to content

Instantly share code, notes, and snippets.

@freakdesign
Last active May 24, 2018 13:40
Show Gist options
  • Save freakdesign/7c47f2bac412ffc3f0cb to your computer and use it in GitHub Desktop.
Save freakdesign/7c47f2bac412ffc3f0cb to your computer and use it in GitHub Desktop.
Quick code to show how to add a sold counter to a product page. Refers to blog post for more info: http://freakdesign.com.au/blogs/news/17335317

Refers to blog post: http://freakdesign.com.au/blogs/news/17335317

First create a new snippet called product-sold-count.liquid. In that file copy and paste the below code:

{% comment %}
  Show current amount sold for a single product (with default variant).
  This assumes that you have created a metafield
{% endcomment %}

{% assign productStartCount = product.metafields.stock.initial | times:1 %}
{% if productStartCount > 0 %}
  {% assign productInventory = product.variants.first.inventory_quantity %}
  <p>{{ productStartCount | minus:productInventory }} sold. Only {{ productInventory }} remain.</p>
{% endif %}

On your product page you can now just include the snippet any place that makes sense:

{% include 'product-sold-count' %}

Now if want to avoid showing negative stock numbers on the page (and just show a message) you can wrap the code in a conditional statement.

{% comment %}
  Show current amount sold for a single product (with default variant).
  This assumes that you have created a metafield.
  Message will show if variant is sold out.
{% endcomment %}
{% if product.variants.first.inventory_quantity > 0 %}
  {% assign productStartCount = product.metafields.stock.initial | times:1 %}
  {% if productStartCount > 0 %}
    {% assign productInventory = product.variants.first.inventory_quantity %}
    <p>{{ productStartCount | minus:productInventory }} sold. Only {{ productInventory }} remain.</p>
  {% endif %}
{% else %}
  <p>Uh Oh! All sold out...</p>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment