5

I have some .md posts, like:

  • 2016-10-01-first_post.md (title: FIRST)
  • 2016-10-03-some_post.md (title: SOME)
  • 2016-10-04-another_post.md (title: ANOTHER)
  • 2016-10-07-my_post.md (title: MY)
  • 2016-10-08-just_a_post.md (title: JUST)

and I created a .html file:

---
layout: default
title: Archives
---
<ul>
{% for post in site.posts %}
<li><a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>

then I got a posts list sorted by file names:

• FIRST
• SOME
• ANOTHER
• MY
• JUST

I want to sort the posts in site.posts alphabetically by post.title, but I don't know how:

• ANOTHER
• FIRST
• JUST
• MY
• SOME

So I'm looking for some help, thx

2 Answers 2

7

You can use sort filter like this : {% assign sortedPosts = site.posts | sort: 'title' %} and then loop over sortedPosts with:

{% for post in sortedPosts %}
  <a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}

Note that you cannot do {% for post in sortedPosts | sort: 'title' %}. You must assign and then loop.

1

You can assign a variable to the site.posts array and sort them using | sort: post.title. Source: https://help.shopify.com/themes/liquid/filters/array-filters#sort

Then loop through the array, just like you normally would through the posts.

3
  • It looks like that syntax might be obsolete. Only sort: 'title' worked for me.
    – l0b0
    Jan 30, 2022 at 5:21
  • but 5+ years ago...
    – Mr. Hugo
    Jan 30, 2022 at 22:36
  • Sure, just making people aware of it.
    – l0b0
    Jan 31, 2022 at 0:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.