Forum

Thread tagged as: Addons, Showcase, Blog

Generating links to the previous and next blog post

This is a reworking of a previous solution by Marc Sanders that can be found in the old Perch forum. While this code is not “battle tested”, hopefully it is of some use to others (like me) who would like this feature.

Post.php

<?php

$slug = perch_get('s'); // sets slug to equal postSlug

$html = perch_blog_post($slug, True);  // stores post in variable to use later

$data = perch_blog_custom(array(
    'filter'=>'postSlug',
    'match'=>'eq',
    'value'=>$slug,
    'skip-template'=>true, 
)); // grabs data of current post

$data = $data[0]; // not sure why this is required, but code breaks without it

$date = $data['postDateTime']; // sets the date variable to the posts published date

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

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

?>

<?php
    if ($html) {
        echo $html; // display post
    }

    if (empty($prev)){
        echo '<div class="blog-nav"><a class="disabled">Prev</a>';
    } else {
        echo $prev;
}

if (empty($next)){
    echo '<a class="disabled">Next</a></div>';
} else {
    echo $next;
}

?>

Post_prev.html

<div class="blog-nav">
    <a href="/articles/<perch:blog id="postSlug" />" class="prev">Prev</a>

Post_next.html

<a href="/articles/<perch:blog id="postSlug" />" class="next">Next</a>
</div>
Alex Blackman

Alex Blackman 0 points

  • 2 years ago

Brilliant, just what I needed - thanks Alex, it worked first time!

For anyone following this, I did spot one thing that my template was masking. The next and back links worked fine, but I was also getting the whole post published alongside the link.

I tried dropping out these lines…

if ($html) {
        echo $html; // display post
    }

And it seemed to sort it.

Perfect. Just what I needed.