Find all pages with same title

hello again!

maybe there is a stupid mistake in my code but I cannot get that to work. i want to get all pages with the same title as the current page and get their url. my code is as follows:

<?php 
if ($pages = page('home')->children()->children()->findBy('title', $page->title())) :
  foreach($pages as $page):
    <a href="<?= $page->url() ?>">link</a>
  endforeach;
endif;
?>

but i get following error:

Call to a member function url() on null

does anybody see my mistake or point me in the right direction for my problem? any help is much appreciated!

findBy() returns single page. You need use filterBy() that returns pages collection.

And you can use grandChildren() instead of double children()->children()

Also, you have to close your php tags before the HTML and open again afterwards:

<?php if ($pages = page('home')->grandChildren()->filterBy('title', $page->title())) : ?>
  <?php foreach($pages as $page): ?>
    <a href="<?= $page->url() ?>">link</a>
  <?php endforeach; ?>
<?php endif; ?>

Also, the if statement in its current form doesn’t make sense for a collection, so better:

<?php $pages = page('home')->grandChildren()->filterBy('title', $page->title()) : ?>
  <?php if ( $pages->isNotEmpty()) : ?>
    <?php foreach($pages as $page): ?>
      <a href="<?= $page->url() ?>">link</a>
    <?php endforeach; ?>
  <?php endif; ?>

works perfectly now. thanks a lot.

and thank you @texnixe for reminding me of the other two points!