3

Basically, I'm trying to show "Out of stock" and disable a button for when none of the variants have stock, and unlimited stock is unchecked.

I've tried this, which isn't working:

{% if product.variants.stock <= 0 and product.variants.unlimitedStock == false %}
    {{ "Out of stock"|t }}
{% else %}
    {{ "Add to cart"|t }}
{% endif %}

2 Answers 2

6

I managed do this with the following:

{% set variants = craft.commerce.variants({
    product: product,
    hasStock: true
}) %}

{% if variants|length <= 0 %}
  Sold out
{% else %}
  Add to basket
{% endif %}

The hasStock criteria takes unlimitedStock into consideration.

if (isset($criteria->hasStock) && $criteria->hasStock === true)
{
  $hasStockCondition = ['or', '(variants.stock > 0 AND variants.unlimitedStock != 1)', 'variants.unlimitedStock = 1'];
  $query->andWhere($hasStockCondition);
}
3
  • Great! I had previously tried {% set variants = craft.commerce.products({hasVariants {hasStock: true )} %}... Cheers!
    – Anders
    Oct 7, 2016 at 17:02
  • According to craftcommerce.com/support/hiding-out-of-stock-products the query in your comment should work. I'm also having trouble with getting any results from this. Mar 10, 2017 at 11:01
  • Should be hasVariant not hasVariants Mar 14, 2017 at 3:57
5

Just in case it's preferred by anyone else, here's a more compact and performant version of pretty much the same technique as Luke's answer:

{% set inStock = product.variants|filter(v => v.hasStock())|length %}

Less readable? Perhaps, but this way also saved me 14 queries compared to the accepted answer.

1
  • love your solution – great :-)
    – Matthias
    Oct 24, 2021 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.