How to conditionally show section on product page?

I would like to display a “SOLD” banner on the product pages of items with inventory quantity of zero. I currently achieve this by applying a “product.sold” template to sold-out products, as shown here: https://mikesgameshop.com/products/sg-0001?_pos=6&_sid=e160847a0&_ss=r

However, this is not ideal because the template has to manually assigned when sold out and changed back if the item is restocked.

Page templates are configured in JSON files, which do not support logic to display a section conditionally. Is there a workaround?

Hi @mikesgameshop ,

yes, we can achieve that do you know custom coding? can you do it by yourself? If not feel free to connect with me via message.

Regards,

Reena

It’s easy please check the below code and you will understand

just set a variable to true if anything is out of stock and you can thus print your message just once.

{% assign out_of_stock = false %}
{% for variant in product.variants %}
  {% if variant.inventory_quantity == 0 %}
    {% assign out_of_stock = true %}
  {% endif %}
{% endfor %}

{% if out_of_stock == true %}
   # Damn Dog, we're out of beers
{% endif %}

Let me know if you need any further help.

@Huptech-Web I suppose the crux of my question would be: In which file would I add such code? Because I can’t add liquid code inside the product template JSON.

SOLUTION

  1. In the editor, select the product template you wish to modify

  2. Add a “Custom Liquid” section

  3. Paste this code:

{%- if product.available == false -%}
  
    ## SOLD!
    

You missed this one, but check out what’s still left!

    Start Shopping
  

{%- endif -%}
  1. Add desired styling with CSS

Hope it helps another seller!