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 %}
5

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);
}
  • 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. – Clive Portman Mar 10 '17 at 11:01
  • Should be hasVariant not hasVariants – Luke Holder Mar 14 '17 at 3:57

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.