Ad

Loop Through Products In Collection And Find Lowest Price (excluding $0 Prices)

- 1 answer

I have a Shopify site with multiple categories. Some products do not have a price (Shopify interests this as $0). All collections are displayed on the front page. I want to loop through all products in each collection and output the minimum price (excluding $0 values).

The current array I'm using is:

{% assign startingFrom = collection.products | sort: 'price' %}
{{ startingFrom[0].price_min | money_without_currency }}

Unfortunately, this captures and outputs $0 values.

What is the best way to loop through values that are higher than $0 and output the lowest price?

I have tried to exclucde zero values:

{% assign startingFrom = collection.products | sort: 'price' %}
{% if 'price' != 0.00 %}
 {{ startingFrom[0].price_min | money_without_currency }}
{% endif %}

This outputs $0.00.

Ad

Answer

{% for product in collection.products %}
  {% if forloop.first %}
    {% assign lowest_price = product.price %}
  {% endif %}
  {% assign new_price = product.price %}
  {% if new_price < lowest_price and new_price != 0 %}
    {% assign lowest_price = new_price %}
  {% endif %}
{% endfor %}

it is not tested but it should work.

Ad
source: stackoverflow.com
Ad