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.
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:
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:
<?php
$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";
}
}
?>