2

I am building a plugin that grants access to a "hidden" (for lack of better words) entry. if a user has purchased a specific product type.

For example, I don't care which piece of clothing the user purchases, just as long as it was of type clothing.

How can I check the users order history to see if they have purchased a qualifying product?

Thank you for any suggestions!

| improve this question | | | | |
  • Could you change your selected answer to mine please. – Luke Holder Oct 1 '19 at 23:27
0

As of Commerce 1.1.1211 you can do:

{% if currentUser %}
{% set order = craft.orders.user(currentUser).hasPurchasables(product.defaultVariant).all() %}
{% if order|length %}
    <strong>I already own this product: </strong> <a href="/shop/customer/order?number={{ order[0].number }}">Order #{{ order[0].shortNumber }}</a>
{% endif %}
{% endif %}
| improve this answer | | | | |
4

First you'll need to grab the user's orders. Then you can check the product type through the purchasable.

Something like this:

{% set orders = craft.commerce.orders.user(currentUser).find() %}

{% if orders|length %}
    {% for order in orders %}
        {% for lineItem in order.lineItems %}
            {{ lineItem.purchasable.product.typeId }} {# 1 #}
        {% endfor %}
    {% endfor %}
{% endif %}

You can take that a step further by doing something like this:

{% set orders = craft.commerce.orders.user(currentUser).find() %}
{% set product = false %} {# set the condition to false by default. #}

{% if orders|length %}
    {% for order in orders %}
        {% for lineItem in order.lineItems if lineItem.purchasable.product.typeId == 1 %}
            {% set product = true %}
        {% endfor %}
    {% endfor %}
{% else %}
    {# No orders found. #}
{% endif %}

...

{% if product %}
    {# User has purchased product type at some point in time. #}
{% else %}
    {# User has never purchased product type. #}
{% endif %}
| improve this 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.