In Products (Craft Commerce), I've set custom fields. Some are texts, some are related to a Category. Actually, there's 2 different categories per variant...

In order to draw the fields, I need to retrieve each category of each variant. enter image description here

Looping thru variants to show text fields is no brainer, but I can't manage to get any category object.

Here's the variant definition:

enter image description here

And the code I put to show what's going on.

{% for variant in product.getVariants() %}
  {{ variant.id }} - {{ variant.sku }} - {{ variant.vendorLength }}
{# This show a CategoryQuery Object #}
  {{ variant.attributeGrainWay }}<br><hr>

{# This show a CategoryQuery Object as well... #}
{% set abc = craft.categories.group('woodGrainOrientation').relatedTo(variant.attributeGrainWay) %}
<pre>{{ abc }}</pre>

No matter what, I can't manage to get what I need. Here's a sample output. enter image description here

As always, your help is greatly appreciated.


1 Answer 1


You haven't executed your category query. Add an execution method to the end of the query, such as .all() or .one(). https://craftcms.com/docs/3.x/element-queries.html#executing-element-queries

  • I can't believe my very eyes !!!! :D I'm good with PHP but obviously lack a few (a lot) notions of twig ! I think I tried different things, like variant.myObject.find() and craft.categories.group... without success... Sure enough YOUR SOLUTION WORKS JUST FINE ! Thanks again, a thank you for all of us sharing your knowledge to make other's life simplier ! :D Commented Apr 21, 2022 at 11:56

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.