Sorting through +300 articles

Hi, one of my sites now counts more than 300 articles. I want to display on the homepage the first XX articles, sorted by date. Now, the query is something like:

$latest = page(‘lung’)->grandChildren()->listed()->sortBy(‘date’,‘desc’)->limit(11);

…but in this way, it’s pretty slow. Any hint about getting better performance? Cache? Database? A different way to sort by date?

Thank you

You can cheat, by saving the latest articles in a pages field and using the page.create:after hook to update it whenever you create a new article.

You can manually populate this first, and then let your hook do the changes thereafter.

This way you never need to loop through all your articles.

The limitation is you have to use the panel to create new articles or you would need to manually trigger the hook somehow.

Thanks. But I was looking for a easier way that doesn’t require me to write and to keep updated too much code… or to duplicate data.

Is there dynamic content on that page? Otherwise a simple page cache could be the easiest solution. Then the first call might still be a bit slow, but all consequent calls come from the cache.

Just wondering why this should be so slow (how slow)? 300 articles isn’t really that much. Do these pages have a lot of content or images? What sort of hosting/server are you using?

Yes, a lot of content and images. The site is hosted on Siteground.

Yes, often the content is dynamically assembled.

What is your pages’ numbering scheme (the num value in your blueprint)?

If you’re already using date (or date time) for your content folder naming scheme then you could sort using the folder name and avoid parsing the content file.

For $page I think it’s $page->dirname().

All the articles are numbered by year and month, so the structure is something like

  • 2022
    – 09
    – 08
    – 07
    – …
  • 2021
    – 12
    – 11
    ecc.

BUT sometimes an articles written in september (09) is published the following month… so this can’t be the way to go…

You said the structure is like:

  • 2022
    • 09
    • 08
    • 07

Do you mean on your website, or for your folder structure?

Surely your folders for each entry is named something like 20220903_Title-of-article?

BUT sometimes an articles written in september (09) is published the following month… so this can’t be the way to go…

Since you’re trying to order your article by the date field, as long as your sorting value num is set to something like num: '{{ page.date.toDate("Ymd") }}' the folder name gets automatically updated whenever your date field value changes via the panel.

So your folder sorting number prefix should always match your date field.

If you say you can’t use the folder name due to publish date being different from written date, you would have the same exact problem with sorting by the date field because the two should be aligned.

1 Like

Sounds promising! I’ll give a try!