1

I am trying to find the last four Channel entries (Named: Post) with a Category relatedTo "Support" (id: 458) AND Tag relatedTo: "Widget1" (id: 469) I've had success using Category or Tag but not both: This Craft Query works for Category

for entry in craft.entries.section('Post').relatedTo('458').orderBy('postDate desc').limit(4).all()

How can I add the dynamic Tag to the Craft query? The dynamic Tag matches the slug of the current page "widget1" or slug of another page "widget2".

Thank you.

1

You'll probably want to read up a bit on relations in the Craft docs, but I think something like this should work

{# First get the category elements #}
{% set supportCategory = craft.categories().id(458).one() %}
{% set widgetCategory = craft.categories().id(459).one() %}

{# Now we use those elements in our query #}
{% set entries = craft.entries().section('Post').relatedTo(['and',
  { element: supportCategory },
  { element: widgetCategory }
]).all() %}

{% for entry in entries %}
  {# ... your code #}
{% endfor %}

I believe the relation needs an element, but you might be able to do something like .relatedTo(['and', 458, 459]).

1

Thank you brianjhanson, you got me 95% there and pointed me to my final solution.

My entry.slug for each page is the exact title of the tag I want to relate to, so this is the code I settled on.

{% set supportCategory = craft.categories().id(458).one() %}
{% set productTags = craft.tags().title(entry.slug).one() %}

{# Now we use those elements in our query #}
{% set entries = craft.entries().section('Post').relatedTo(['and',
   { element: supportCategory },
   { element: productTags }
]).orderBy('postDate desc').limit(4).all() %}

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.