Simple Tag Cloud in Statamic

How to create a very simple tag cloud in Statamic using some native taxonomy tags and applying a quick algorithm in your default template.

I was looking recently how to include a tag cloud on this site. There are no plugins available as of yet for a tag cloud generator for Statamic, so I headed to Google. What I found was this very in-depth article on Tag Cloud Algorithm/Logic/Formula. It is well worth a read through even if just to get a gist of the math involved.

So applying this newly acquired knowledge, this is what I came up with.

In your template add the following. When the tags are generated as links we make use of the link’s title attribute to capture the metric value to proceed with our calculation.

        
<ul id="tag-cloud">
  {{ taxonomy:listing from="articles" type="tags" }}
  <li>
    <a href="{{ url }}" title="{{entries:listing folder='articles' conditions='tags:{name}'}}{{ if first }}{{ total_results }}{{endif}}{{ /entries:listing }}">{{ name|title }}</a>
  </li>
  {{ /taxonomy:listing }}
</ul>

In your layout template footer add the following. It is slightly adjusted form the article mentioned above.

<script>
  $(document).ready(function() {
    function processCloud(id, max) {
      var cloud = document.getElementById(id);
      if (!cloud) return;
      var tags = cloud.getElementsByTagName("a");
      for (var i = 0; i < tags.length; i++) {
        var tag = tags[i];
        var title = tag.getAttribute("title");
        var f = title.substring(title.indexOf(":") + 1);
        var fontSize = (150.0 * (1.0 + (1.5 * f - max / 2) / max)) + "%";
        tag.style.fontSize = fontSize;
      }
    };
    processCloud("tag-cloud", 30);
  });
</script>

Here, getElementById is a utility function that gets the element from the document based on a given id which in this case is tag-cloud. So, your tag cloud can be placed in a div element with an id and that’s the id you pass to the processCloud function along with the max value which gives the cloud its size/intensity. Lower numbers for larger intensity.

I welcome any refinements that you can suggest.