How do I cre­ate an Archives page and man­age the URLs using Routes?

Many websites have an archive page that displays content based on the date in the URL.

To create an archive page in Craft we need to take a couple of steps:

  1. Add a new route so that our page knows what template to load
  2. Customize our craft.entries tag to query for the right content based on that date

In this article we will focus on creating a route to your archive page template, and analyzing the details of what that route is doing.

To make your archive page to be based on the year and month of your posts, add the following to the array in your craft/config/routes.php file.

return array(
  'blog/(?P<year>\d{4})/(?P<month>\d{2})' => 
  'blog/index'
);

This route will allow us to have URLs such as blog/2012/10 and it will tell Craft that we want to use our blog/index.html template to output the archive page. Let's take a closer look at the details:

blog First segment of the url matches the word blog
/ Match a forward slash in the URL
( Parentheses begin to create a stored variable pattern
?P This letter combination allows us to create a variable pattern
<year> The word in the angle brackets is our variable, which will be accessible on the page as {{ year }}
\d This means our pattern can include any digits 0-9
{4} A number within curly brackets tells us that their must be 4 digits total for a match
) End parentheses denotes the end of our stored variable pattern
/ Match a forward slash in the URL
( Parentheses begin to create a stored variable pattern
?P This letter combination allows us to create a variable pattern
<month> The word in the angle brackets is our variable, which will be accessible on the page as {{ month }}
\d This means our pattern can include any digits 0-9
{2} A number within curly brackets tells us that their must be 2 digits total for a match
) End parentheses denotes the end of our stored variable pattern

Level up in Craft CMS with practical examples, snippets, and patterns.
Craft The Planet emails are sent out several times a week.