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

How to show related posts with Perch blog

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 show related posts on this site and for posts in the News section of my CVW Web Design site. For example, the What is my USP post displays two related articles in the sidebar. And the post you are reading now displays two related posts from the Perch category in the sidebar. Here's how I have done that with Perch blog.

Firstly, I put on my developers hat (~ grin) and searched the Perch documentation and forum for ways of doing this. There were two posts in the forum that helped me. The code below is derived from those.

This code goes in your post page where you want to display the related posts.

//Get the categories for the current post 
$categories = perch_blog_post_categories(perch_get('s'), array(
 'skip-template'=>true, ));

//The post may be in more than one category, so we need to loop through these and get the category slugs
if (count($categories)) {
 $cat_slugs = array();
 foreach($categories as $cat) {
 $cat_slugs[] = $cat['catSlug'];

//Display two related posts, ordered by date, excluding the current post
 'filter' => 'postSlug',
 'match' => 'neq',
 'value' => perch_get('s'),
 'category' => $cat_slugs,
 'sort' => 'postDateTime',
 'sort-order'=> 'DESC',
 'count'=> 2,
 'template'=> 'blog/post_in_list_related.html',

I'm using perch_blog_post_categories to get the blog categories for the current post. I don't want to display these on the page so I use skip-template to give me an array. I check that the array contains at least one item with an if statement for the next part.

The post may be in more than one category so I loop through to get the category slugs in an array called $cat_slugs which I use as the category value in the next section.

Then, I use perch_blog_custom to display two related posts (but excluding the current post) in those categories. I display these in date order with my post_in_list_related.html template (very similar to the default Perch post_in_list.html template).

OK, that's it. Hope this is useful. All suggestions for improvements are welcome!

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

Comments are OFF for this post.

© 2024 Clive Walker