Does your site run on Perch CMS? Hire me to help. Perch CMS Development

Grouping blog posts by year with Perch

Posted on by Clive Walker in Perch

I wrote this post a while back. The content can still be relevant but the information I've linked to may not be available.

I wanted to test a page that groups my blog posts according to the year of publication. The page would have headings for each year with a list of posts underneath. This is what I've done to achieve that using Perch CMS and its Blog app.

Here's the demo.

Perch makes it easy to sort and display blog posts using perch_blog_custom. Let's start with that. Here's what I'm using in the page:

<?php 
// get the blog posts, sorted by posting date
 perch_blog_custom(array(
    'sort' => 'postDateTime',
    'sort-order' => 'DESC',
    'count' => '2000',
    'template' => '/blog/post_in_list_years.html',
 ));
 ?>

I'm sorting the blog posts by date in descending order. I want to display all blog posts so I don't need to use a date range. I need to set a count that's higher than the number of posts because the default for perch_blog_custom is 10.

Now, I need to display the posts with the year headings. Here's my post_in_list_years.html template. It goes in /perch/templates/blog.

<perch:before>
    <ul>
</perch:before>
    <perch:if different="postDateTime" format="Y"> 
        <li class="yearheading">
            <h2><perch:blog id="postDateTime" format="Y" /></h2>
        </li>
    </perch:if> 
         <li><a href="<perch:blog id="postURL" />" rel="bookmark" class="entry-title"><perch:blog id="postTitle" /></a></li>
 <perch:after>
     </ul>
</perch:after>

I don't want the year displayed for every post, but only for each year group. The trick here is that I'm using <perch:if> to show the year heading only if it's different from the previous value. This means that I can group my posts by year.

<perch:if different="postDateTime" format="Y">

I use format = "Y" for the comparison and for displaying the year. The posts are listed underneath the year heading. Yay!

Let me know if you have other ways of doing this. I can think of a couple of improvements that I want to make.

Does your site run on Perch CMS? Hire me to help. Perch CMS Development

Comments

  • Caron:

    08 Sep 2015 15:49:14

    Thanks for posting this solution, so helpful.

Comments are OFF for this post.

© 2024 Clive Walker