1

on my new project I decided to show in the page grid variants rather than products, but I am experiencing difficulties, since I am supposed to filter the record set based on a category relation of the product (which holds the variants) rather then on the variants themselves.

If I had to show products in the grid, this would be sufficient:

{% paginate craft.products.relatedTo(currentCategory).limit(12) as pageInfo, pageProducts %}

But since I want to output the variants my starting point is:

{% paginate craft.variants.relatedTo(...?...).limit(12) as pageInfo, pageProducts %}.

A variant holds a relation named product which I do not know how to use in the query builder.

I tried to play a bit with where, having and so on but no luck.

Any suggestions?

1 Answer 1

1

Try this:

{% set relatedProducts = craft.products().relatedTo(currentCategory) %}

or if you want specific field

{% set relatedProducts = craft.products().relatedTo({
    targetElement: currentCategory,
    field: 'productCategoryFieldInTheProduct'
}) %}

and after

{% set variants = craft.variants.hasProduct(relatedProducts) %}

Where: currentCategory - category query, category element or ID

3
  • Thanks @RomanAvr I'm gonna try this next week. I will keep you posted.
    – Masiorama
    Commented Oct 14, 2022 at 6:55
  • You are welcome. Just tested on craft & commerce 3.x, worked for me
    – RomanAvr
    Commented Oct 14, 2022 at 22:05
  • 1
    Just tested on commerce 4 and it works. Sorry for the delay.
    – Masiorama
    Commented Oct 19, 2022 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.