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 %}
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 '16 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 '17 at 11:01
  • Should be hasVariant not hasVariants Mar 14 '17 at 3:57
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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