Related pages fallback options

Okay, I wanted to list 3 related articles that are siblings on a single entry page, not including itself. That part is easy:

<?php foreach ($page->siblings(false)->shuffle->limit(3) as $item) : ?>

But in case there weren’t at least 1, 2, or even 3 siblings, I wanted to include another section of the site that clearly had items that enough grandchildren: bigsection
…(although if there’s an easier way, I’d love to see that, too).

So, my idea is, if there’s less than 1 sibling, get 3 from bigsection. If there’s less than 2, get 2 from bigsection, etc., etc.

  <?php $related = $page->siblings(false)->shuffle()->limit(3) ?>
  <?php $relatedcount = $page->siblings(false)->count() ?>
  <?php $unrelated = page('bigsection')->grandChildren()->shuffle() ?>

  <?php if ($relatedcount < 1): ?>
    <?php snippet('minicards', ['minicards' => $unrelated->limit(3) ])?>

   <?php elseif ($relatedcount < 2): ?>
    <?php snippet('minicards', ['minicards' => $related ])?>
    <?php snippet('minicards', ['minicards' => $unrelated->limit(2) ])?>

   <?php elseif ($relatedcount < 3): ?>
    <?php snippet('minicards', ['minicards' => $related ])?>
    <?php snippet('minicards', ['minicards' => $unrelated->limit(1) ])?>

   <?php else : ?>
    <?php snippet('minicards', ['minicards' => $related ])?>
  <?php endif ?>

Although the logic of this, to me, seems straightforward, the code appears excessive.
Since I’m a php noob, I’d love to hear any solutions you may have. Cheers!

$limit   = 3;
$related = $page->siblings(false)->shuffle()->limit($limit);
$count   = $related->count();
if ( $count < $limit ) {
    $unrelated = page('bigsection')->grandChildren()->shuffle()->limit($limit-$count);
    $related   = $related->add($unrelated);
snippet('minicards', ['minicards' => $related ]);
1 Like

I would use a different approach: What you want is 3 articles from bigsection minus the ones you already have, but only if the difference is greater than 0. So, get the count of articles, calculate the difference (3 - count), if it is less or equal 0 you are fine, if not, get the difference-count from bigsection.

This approach would be easy to change if one day you would like to get 4 articels instead of 3. You just need to change the difference calculation.

1 Like

Thank you both. That is much cleaner. :star_struck: