Similar articles, excluding current/active one


I’m trying to display three similar articles on an article page.

<?php foreach($pages->find('blog')->children()->listed()->shuffle()->paginate(3) as $article): ?>

So far so good, now I want to exclude the current/active one. I’ve tried to play with ->not($page->isActive()) but currently stuck.

Appreciate the help!

$page is always the current page (unless you redefine it anywhere):

$related = $pages->find('blog')->children()->listed()->not($page)->shuffle()->limit(3);

Or simpler:

$related = $page->siblings(false)->listed()->shuffle()->limit(3);

You don’t want to paginate here, use limit() to limit your collection to a number of items.

Methods that start with is or has return a boolean.

The code you used above is not recommended, because you should check if the blog page exists before calling the children() method:

if ($blogPage = page('blog')) {
  $related = $blogPage->children()->....;
1 Like

Awesome, worked like a charm!

I’m currently trying to show this section of “more posts” at the bottom of an article, but only if there are more than 1 post.

I’m trying something like:
<?php if ($pages->parent()->count() > 1): ?>

Any suggestions?

Found it!

<?php if ($page->parent()->children()->count() > 1): ?>

That code doesn’t make sense. $pages is a pages collection and doesn’t have a parent method.

You want to know if the current page has siblings:

$siblings = $page->siblings(false);
if ($siblings->isNotEmpty()) {
  // do stuff

Yes sorry, my mistake. But adding ->children() did the trick.