Craft Commerce: Filter completed orders based on a product category field 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 %}
  &lt;input type=&quot;hidden&quot; name=&quot;fields[productGroup][]&quot; value=&quot;{{ catId }}&quot;&gt;
{% endfor %}

Now I have categories assigned to an order and can easily filter them using .relatedTo(), like this:
{% set ordersQuery = craft.orders().relatedTo(...) %}