I know how to filter entries or products based on a category field with .relatedTo, but how can I filter completed orders based on a product category field?

In this specific case, I have an overview of completed orders. I would like to select a category and show only those orders that contain products with the selected category.

Any hints in the right direction are greatly appreciated!


Managed to solve this.

First, I've added a categories field to the order form.

On the checkout page I loop over all lineItems in the cart and collect the category id's like this.

{% set categoryIds = [] %}

{% for item in cart.lineItems %}
  {% set categories = item.purchasable.product.productGroup.leaves().all()%}
  {% for category in categories %}
    {% if category.id not in categoryIds %}
      {% set categoryIds = categoryIds|merge([category.id]) %}
    {% endif %}
  {% endfor %}
{% endfor %}

Then, I submit the categories using a hidden input.

{% for catId in categoryIds %}
  <input type="hidden" name="fields[productGroup][]" value="{{ catId }}">
{% endfor %}

Now I have categories assigned to an order and can easily filter them using .relatedTo(), like this:

{% set ordersQuery = craft.orders().relatedTo(...) %}

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.