Blog Archive using virtual pages?

I’m trying to code a Wordpress-style feature which will group together all Blog posts by year and month. What I’d like to achieve is a list that looks something like:

  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • (etc.)

…and have each one of those entries to to a virtual page, e.g. March 2022 would go to /blog/archive/2022/03. On that page would be a (paginated) list of all the blog entries for that month. I already have all the blog entries in a collection, so I can group and filter them in the factory as needed to populate the content for the page.

I think that virtual pages should work here, but I’m not sure on the syntax for the factory. Presuming I have am array that looks something like [2022: [03, 02, 01], 2021: [12, 11, …], 2020: […], …], how could I loop through this in the factory? Or are virtual pages not the best approach for this?

You could use a route rather than virtual pages

'routes' => [
  [
    'pattern' => 'blog/archive/(:any)/(:any)',
    'action' => function($year, $month) {
      // filter collection of articles here
    }
  ]
]
1 Like