How to Add Next and Previous Blog Post Links with Perch

by Clive Walker

Use three queries to get data from the current post and next and previous posts in order to display Next and Previous post links.

Here's the code I use to add Next and Previous Post links to each blog post on this site. I've used this on a few sites and it's been described in different ways on the old Perch forum. But, I thought it would be useful to pull it together here.

Firstly, near the top of my page, we use perch_blog_custom to get the current post's data.

// get the post data, put it into $post variable
$post = perch_blog_custom([
  'filter'        => 'postSlug',
  'match'         => 'eq',
  'value'         => perch_get('s'),
  'skip-template' => true,
  'return-html'   => true
]);

// write the values from the array stored in $post to variables
  $date  = $post[0]['postDateTime'];
  $html   = $post['html'];

Now, I need to get the data from next and previous posts so that I can use this in the Next and Previous Links. I put this data into $next and $prev variables:

$prev = perch_blog_custom([
      'count'=>1,
      'filter'=>'postDateTime',
      'match'=>'lt',
      'sort'=>'postDateTime',
      'sort-order'=>'DESC',
      'value'=>$date,
      'template'=>'blog/post_prev.html'
        ], true); // stores prev post in a variable to use later
       
$next = perch_blog_custom([
      'count'=>1,
      'filter'=>'postDateTime',
      'match'=>'gt',
      'sort'=>'postDateTime',
      'sort-order'=>'ASC',
      'value'=>$date,
      'template'=>'blog/post_next.html'
      ], true); // stores next post in a variable to use later

The Next and Previous templates in the above are similar. Here's a simplified version of my blog/post_next.html template.

<li class="next">
    	<a href="/blog/<perch:blog id="postSlug" />" class="prev"><perch:blog id="postTitle" />
    	     	<time class='published' datetime="<perch:blog id="postDateTime" type="date" label="Date" time="true" format="Y-m-d H:i:s" />">
<perch:blog id="postDateTime" type="date" time="true" format="%d %B %Y" /></time> 
    	</a>
    </li>
</ul>

Finally, on my page, I can output the post and the Next and Previous Post links like this:

echo $html; // the post

// Previous and next post navigation
  if (empty($prev)){
          echo '<ul>';
    } else {
          echo $prev;
    }
  if (empty($next)){
      echo '</ul>';
    } else {
          echo $next;
  }

OK, that's it!

You should be able to see at least the Previous Post link below.