Related Posts by Tags

I’m trying to get this post working in Kirby 3, but it doesn’t seem to be working. It’s not returning any related posts.

Is there a better way to do this in Kirby 3?

I’m trying something along these lines, but not sure this is possible:

$related = $children->filterBy('tags', $tags, ',')->limit(3);

Could you please post some more details? What is $children, what is $tags?

You might want to check out one of my plugins:

(they do basically the same, but differently)

I’ll look into those, thanks.

Here’s the code. I was just trying to do something simple based on tags in posts. So this was in my post.php controller.

//pull tags for current post
$tags = $page->tags()->split(',');

//get all visible blog posts
$children = page('blog')->children()->listed();

//build related pages array to send back to post
$related = $children->filterBy('tags', $tags)->limit(3);

I’m reading the filter() method now, instead of filterBy().

//pull tags for current post
$tags = $page->tags()->split(',');

//get all siblings posts
$siblings = $page->siblings(false)->listed();

//build related pages array to send back to post
$related = $siblings->filter(function($item) use($tags) {
  return count(array_intersect($tags, $item->tags()->split(','))) > 0;
})->limit(3);
1 Like

Beautiful. That’s works wonders. I didn’t even catch the children vs. siblings wording I was using. Nice!

FYI, looks like there’s a filter() missing before the function, right? Here’s what I’m using.

$related = $siblings->filter(function($item) use($tags) {
	return count(array_intersect($tags, $item->tags()->split(','))) > 0;
})->limit(3);
1 Like

Yes, of course, sorry, will correct above.