Posts Module Year/Month Archive List
Created 7 years ago by blovelessIt took me a while to figure all this out, so I'm putting it here so other people can benefit from this! Here is how I created a year/month archive lists (with counts of the number of posts in each year and month) in the posts module using the entries plugin.
{% set years = entries('posts').selectRaw('DISTINCT YEAR(`publish_at`) as year').orderByRaw('YEAR(`publish_at`)').get() %}
{% for year in years %}
{% set yearCount = entries('posts').whereRaw('YEAR(`publish_at`) = ' ~ year.year).count() %}
<div class="archive-year">
<a href="/posts/archive/{{ year.year }}">{{ year.year }} ({{ yearCount }})</a>
</div>
{% set curYearMonths = entries('posts').selectRaw('DISTINCT MONTHNAME(`publish_at`) as month_name, MONTH(`publish_at`) as month').orderByRaw('MONTH(`publish_at`)').whereRaw('YEAR(`publish_at`) = ' ~ year.year).get() %}
{% for month in curYearMonths %}
{% set monthCount = entries('posts').whereRaw('YEAR(`publish_at`) = ' ~ year.year ~ ' and MONTH(`publish_at`) = ' ~ month.month).count() %}
<div class="archive-month">
<a href="/posts/archive/{{ year.year }}/{{ month.month }}">{{ month.month_name }} ({{ monthCount }})</a>
</div>
{% endfor %}
{% endfor %}
Let me know if you have a better way to do this or if you have any input!
bloveless
—
7 years ago
Updated the queries to remove some of the whereRaw queries.
{% set years = entries('posts').selectRaw('DISTINCT YEAR(`publish_at`) as year').orderByRaw('YEAR(`publish_at`) desc').get() %}
{% for year in years %}
{% set yearCount = entries('posts').whereYear('publish_at', year.year).count() %}
<li class="archive-year {% if year.year == archive_year %}opened{% endif %}">
<a class="open-year" href="javascript:;"><i class="fa fa-caret-right"></i></a>
<a href="/posts/archive/{{ year.year }}">{{ year.year }} ({{ yearCount }})</a>
<ul>
{% set curYearMonths = entries('posts').selectRaw('DISTINCT MONTHNAME(`publish_at`) as month_name, MONTH(`publish_at`) as month').orderByRaw('MONTH(`publish_at`)').whereYear('publish_at', year.year).get() %}
{% for month in curYearMonths %}
{% set monthCount = entries('posts').whereYear('publish_at', year.year).whereMonth('publish_at', month.month).count() %}
<li class="archive-month {% if month.month == archive_month %}selected{% endif %}">
<a href="/posts/archive/{{ year.year }}/{{ month.month }}">
<i class="fa fa-caret-right"></i> {{ month.month_name }} ({{ monthCount }})
</a>
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
ryanthompson
—
7 years ago
Thank you! If you interest, here is a realization of calendar in Vue, in ES5 style-code. Templates:
JavaScript: