How to List all the posts on your site by year
Drive 20-40% of your revenue with Avada
In order to help your customers easily see all of your posts in each year, you need to show all of your posts right on your website and arrange them in multiple years. It is really important for you to read carefully this instructional writing on How to list all your posts on your site by year if you want to make this list on your own page.
How to list all your posts on your site by year
Step 1: How to create a layout
Before taking an official step on adding the code to list your posts by year on your website, you need to know How to create a layout that will show all your posts.
In _layouts
directory, create a new file called home.html
and add the following logic:
---
layout: default
---
{{ content }}
<ul class="myposts">
{% for post in site.posts %}
<li><a href="{{ post.url }}">{{ post.title}}</a>
<span class="postDate">{{ post.date | date: "%b %-d, %Y" }}</span>
</li>
{% endfor %}
</ul>
Step 2: Create blog.md
Then, in your root directory, create a file called blog.md
and specify the home
layout:
---
title: Blog
layout: home
---
From that, contents of blog.md
will be pushed into the {{ content }}
tag in the home
layout which will be pushed into the {{ content }}
tag of the default
layout.
Step 3: Generate post list
Now, just embark on adding the code to create a list of posts in multiple tags on your website.
In site.post
directory which helps you show all your posts in a list, you can add more information to order them in different years. When the year changes, we will output the year as a title and then carry on outputting the post details. Add exactly this following code to take into action:
...
{% for post in site.posts %}
{% capture current_year %}{{ post.date | date: "%Y" }}{% endcapture %}
{% if current_year != previous_year %}
{% unless forloop.first %}
</ul>
{% endunless %}
<h2>{{ current_year }}</h2>
<ul>
{% assign previous_year = current_year %}
{% endif %}
<li><a href="{{ post.url }}">{{ post.title }}</a></li>
{% if forloop.last %}
</ul>
{% endif %}
{% endfor %}
...
From now, your customers can see all your posts arranged in detailed years.
Conclusion
With some very simple steps above, we hope that this tutorial provides useful information in your web development process. It is much easier for your customers when they visit your website and find your posts. Keep following us in next informative posts to get surprising things. Thank you for spending time reading!