Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Jekyll tags by number of posts

The code which displays tags for the Jekyll theme I am using is given below. It currently shows tags in alphabetical order. What should I change to sort via post count? I saw a similar question but the code they used was very different from what is in this theme.

{% capture site_tags %}{% for tag in site.tags %}{{ tag | first | downcase }}{{ tag | first }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' | sort %}
{% capture site_tags %}{% for tag in site_tags %}{{ tag | split: '' | last }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign site_tags = site_tags | split: '' %}

{% assign post_count = site.posts | size %}
{% capture tag_counts %}{% for tag in site_tags %}{{site.tags[tag] | size | times: 10 | plus: post_count | minus: 1 | divided_by: post_count }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign tag_counts = tag_counts | split: ',' %}

<ul class="tags quick-links">
{% for tag in site_tags %}
    {% assign tag_data = site.data.tags[tag] %}
    {% capture tag_classes %}tag tag-size-{{ tag_counts[forloop.index0] }} tag-{{ tag | slugify }}{% endcapture %}
    {% capture tag_name %}{% if tag_data.title %}{{ tag_data.title }}{% else %}{{ tag }}{% endif %}{% endcapture %}
    <li><a href="{{ include.baseurl }}#{{ tag | slugify }}" class="{{ tag_classes }}">{{ tag_name }}<span class="count">{{ site.tags[tag] | size }}</span></a></li>
{% endfor %}
</ul>

The link to the file. This is the theme I used.

Screenshot: enter image description here

like image 896
K. Sreeman Reddy Avatar asked Nov 18 '25 04:11

K. Sreeman Reddy


1 Answers

change {{ tag | first | downcase }} to {{ tag[1].size | plus: 1000 }} for sorting with post count.

The problem left is the post will appear in ascending order which can easily solved by reversing the order by adding reverse after tag are sorted.

{% capture site_tags %}
  {% for tag in site.tags %}
    {{ tag[1].size | plus: 1000 }}&#x1F;{{ tag | first }}
    {% unless forloop.last %}&#x1E;{% endunless %}
  {% endfor %}
{% endcapture %}
{% assign site_tags = site_tags | split: '&#x1E;' | sort | reverse %}
like image 82
Chandan Avatar answered Nov 21 '25 08:11

Chandan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!