Update Stock Quantity On Product Page When Variant Changes (To Refresh Or Not To Refresh?)

[I’ve already read a few other questions about this, but they all revolve around different things displaying]

I hope you can help - I’m trying to make the stock count update so that it will display the current # available for the variant that’s been selected. As you no doubt know, regardless of the quantity in stock for other variants, the “in stock” number remains as whatever the first variant’s count was.

I’m only slightly past novice level at coding, and so prefer to add a Custom Liquid block to add liquid code whenever possible in the Theme Editor, instead of hardcoding in the back end (which has to be re-added with every theme version update).

I’m using Craft theme 15.0, here is the code in the block that I have so far. Maybe this can be tweaked? Or does it have to all be done in the back end? I’m not looking for a full page refresh, but if that’s the only option, please advise.

{% assign current_variant = product.selected_or_first_available_variant %}
  <div class="inventoryNote form__label">
  {% if current_variant.available %}
    {% if current_variant.inventory_quantity > 0 and current_variant.inventory_quantity <= 10 %}
        In stock:  <b>{{ current_variant.inventory_quantity }}</b> available
    {% elsif current_variant.inventory_quantity > 10 %}
        In stock: <b>10+</b> available
    {% endif %}
  {% endif %}
  </div>

Any help folks can offer is greatly appreciated, thank you!

1 Like

The code you’re using:
{% assign current_variant = product.selected_or_first_available_variant %}

This only gets the initial variant when the page first loads. Shopify Liquid runs server-side, not dynamically in the browser. So once the page is rendered, switching variants using JavaScript does not re-run that Liquid code.

As a result:

The stock quantity you display doesn’t change when the user selects a new variant.

It always shows the count for the first available variant, not the selected one.

1 Like

@moshbray pretty much conveyed the issue that does not update your stock count.

You can listen for the variant change event, select the current variant and then look for the if conditions.

Also to answer your question this is something you will most probably want to be doing in the theme code editor in the backend.

Best

Shadab

After a lot of digging, and pretty much all solutions involve editing the files in the backend (which I’d rather not do), I decided to look for an app instead.

FYI if anyone else is having this problem, this app is free (at time of posting) and creates a small widget that displays on the product page: Jedi - Stock Counter.

It does some other things too but honestly that’s all I was looking for. And you can change the text. BTW I’m not affiliated with these guys in any way, just thought I’d post my solution. Seems there’s a lot of people other than me who find this an issue.