How to implement custom tag ordering

Hello there.

I am trying to perform a custom ordering of topic tags by their tag group name value.

I have been looking at theme components and I think that’s the way to go but I would like some opinion on this as well as any pointers as this would be my first theme component.

Cheers

1 Like

I ended up using the tag description field to store a integer to simulate the ordering I wanted. The thing is the tag group is not exposed in the tag structure nor the DOM so that’s why I use this way.

After that using an head code snippet from the theme editor I injected the following script into the DOM.

This allowed me to reorder the tags dynamically. While it’s a “hack” as of now at least It’s working.

<script type="text/discourse-plugin" version="0.8">
  api.addTagsHtmlCallback(function(topic, params) {
    const containers = document.querySelectorAll(".discourse-tags");
    for (const container of containers) {
      const children = Array.from(container.children);

      children.sort((a, b) => {
        const orderA = parseInt(a.getAttribute("title"));
        const orderB = parseInt(b.getAttribute("title"));
        return orderA - orderB;
      });

      children.forEach(child => container.appendChild(child));
    }
  }, {priority: 100});
</script>