Using liquid to sort posts alphabetically
It can be done without a plugin, which means that it works with Github Pages.
You have to use some ugly string manipulation tricks, though.
I used a similar approach to implement a tag page (that lists all posts for each tag).
Same approach, slightly modified:
{% capture posts %}
{% for post in site.posts %}
|{{ post.title }}#{{ post.url }}
{% endfor %}
{% endcapture %}
{% assign sortedposts = posts | split: '|' | sort %}
{% for post in sortedposts %}
{% assign postitems = post | split: '#' %}
<a href={{ postitems[1] }}">{{ postitems[0] }}</a><br>
{% endfor %}
Beware:
You need two different separator characters inside the first loop (and of course again in the split
calls later on).
In order for this to work, both characters must not occur in any of the post titles or URLs!!
I'm using |
and #
in this example, which works for me (I just tested it with my blog). But you might need to use different characters, depending on your post titles and how your URLs are constructed.
Bonus:
If you want to display only the posts in a certain tag/category (and not all posts), you can change the first for
loop (the one inside the capture
) to one of these:
{% for post in site.tags['whatever'] %}
{% for post in site.categories['whatever'] %}
According to the documentation, to filter an array by one of its field, you can use :
{% assign sortedPosts = site.posts | sort: 'title' %}
Then the sortedPosts
variable will contain the sorted array.
The documentation can be found here : https://docs.shopify.com/themes/liquid/filters/array-filters#sort