Displaying related links to nonexistent pages

I’m using the following foreach loop to grab related pages and display them in a list on a page. The old Related Pages plugin render links to pages that were listed as “related” but did not exist yet. This made it handy to check for 404s.

<ul class="src">
    <? $n=0; foreach($page->related()->pages() as $related): $n++; ?>
    <li><a href="<?php echo $related->url() ?>"><?php echo html($related->title()) ?></a></li>
    <?php endforeach ?>

The way that the current version of Kirby handles nonexistent pages in this loop is different … as it ignores nonexistent when rendering the list.

Is there any way to override this so that nonexistent page are included?

When looking at the source code, it seems that non-existing pages were ignored in that old plugin as well.

If the page object does not exist and you try to call a method like url()on it, you would run into an error, so that would not make sense.

1 Like

Actually, the old plugin didn’t completely ignore non-existing pages. It still rendered a link, but since it couldn’t reference an actual page, it displayed it like this:


It used the word “Term” for the link text, since it wasn’t able to extract that field from a non-existent page.

What you could do, is instead of using the pages() method, use the toStructure() method to get the contents of the field and then do whatever you like if the page does not exist:


$related = $page->related()->toStructure();

foreach($related as $r) {
  $p = page($r->value());  
  // check if $p is a page object
  if(is_a($p, 'Page')) {
    echo $p->title();
  } else {
   // do whatever you want here, but do not use page methods
    echo "The page does not exist";

Thank you, Sonja!

I’ll definitely be able to work with this solution.

1 Like