Group collection items by year on a page


#1

I’m trying to create a page that organizes the content of my website by year. My website is using collections, rather than posts, and I’m having a difficult time creating a page that groups all collection items by year.

Here’s where I’m at:

{% assign research = site.documents | where:"research","true" %}
	{% assign postsByYear = research | group_by_exp:"post", "post.date | date: '%Y'" %}
	{% for year in postsByYear %}
	  <h3 id="{{ year.name | slugify }}">{{ year.name }}</h3>
		{% for post in year.items %}
		{% assign postYear = post.date | date:"%Y" %}
				<h4><a href="{{ post.url }}">{{ post.title }}</a></h4>
				<h6>{{ post.author }}</h6>
				<div>{{ post.abstract | truncatewords: 75 }} </div>
			{% endfor %}
	{% endfor %}

This returns posts from the past three years in an odd order: 2017, 2018, 2016. I can’t figure out why it’s not starting with the current year.

Any ideas?


#2

Collections aren’t required to have the date in them like posts - so are you adding a front matter field for the date?

Have you tried the sort filter? or maybe some dates aren’t formatted the same as others?


#3

hey thank you so much for this! it worked perfectly!