1

I have a digital product, with a landing page, and I want to know if the connected user has already bought the product so I can give him access to the content.

1

There is a direct way to find this out.

Here's an example. Note the id you supply must be the specific purchasableId, not the product id (so the defaultVariant.id or variant.id).

{# Has the customer explicitly bought the XXX product? Returns 0 (==false) or >= 1 (==true) #}

{% set purchasedXXX = craft.orders()
    .user(currentUser)
    .hasPurchasables(10637)
    .isCompleted()
    .count()
%}

You can then use that as just

{% if purchasedXXX %}
 ...
{% endif %}
| improve this answer | |
0

Try something like this:

  {% set found = false %}
  {% set orders = craft.orders()
    .customer(craft.commerce.customer)
    .all() %}
  {% for order in orders %}
    // here you could / should also check if the order was paid
    {% for lineItem in order.lineItems %}
      {% if lineItem.purchasableId == yourProductId %}
        {% set found = true %}
      {% endif %}
    {% endfor %}
  {% endfor %}
  {% if found %}
      // user has bought product before 
  {% endif %}

There might be more efficient query-wise.

| improve this answer | |
  • There's a much more direct way available with recent Commerce versions, see my answer. – Jeremy Daalder Sep 16 at 2:32

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.