2

Is it possible to output tags for an entry page in the order they were added to related entry?

For example on a News page I would like to output any/all tags added to the News article on the specific article page in the order the tags were added to that article, I currently output the tags using the following:

        {% for tag in craft.tags.relatedTo(entry) %}
            <li>{{ tag }}</li>
        {% endfor %}

This works great as it only outputs the tags that have been added to that entry, but it shows the tags in the default title ascending order rather than reflecting the order on the entry.

I can switch the order by setting it to desc on the title .order('title desc') and I've also read through the docs on ordering but I'm still not sure how to achieve this.

Thanks,

  • Have you tried using fixedOrder? I'm not sure how you would know the id's of the tags that are getting used for any given entry though... – Damon Sep 22 '15 at 4:43
  • 1
    Yep, but no luck. I managed to solve it using 'sortOrder'. I'll post my code later in case anyone else is trying the same thing – JRW Sep 22 '15 at 6:47
  • Awesome! Please do! – Damon Sep 22 '15 at 10:46
1

I managed to solve this by defining the tags as a ElementCriteriaModel. Instead of using the code above I used the following:

{% set tags = entry.tagsFieldHandle %}

{% if tags | length %}
   {% for tag in tags %}
      <li>{{ tag }}</li>
   {% endfor %}
{% endif %}

Explained further in the Tag section in the docs. {% set tags = entry.tagsFieldHandle %} is a shortcut for:

{% set tags = craft.tags({
   relatedTo: { sourceElement: entry, field: "tagsFieldHandle" },
   order:     "sortOrder",
   limit:     null
}) %}

This meant I didn't need to define the entry relation as the model does that be default and it also sorted the tags as they were defined in the entry with the "sortOrder" (which is also default).

| improve this answer | |
  • Thank you for posting this solution. I was needing this exactly thing. – Anna_MediaGirl Oct 7 '15 at 3:29
  • You're welcome, I'm glad it helped – JRW Oct 7 '15 at 8:56

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.