Modifying navigation hyperlinks to first child page and retrieving its image

My hierarchy of pages is this:

Category (pages)
…Project (pages)
……Image (page)
……Image (page)
…Project (pages)
……Image (page)
……Image (page)

In the code below I list out the categories (without links) and projects (with links), but I would like to modify the project hyperlinks to be the first child image page under the project. The text should still be the project name. I was reading about routing but I don’t think that’s the correct solution as I still need the project page to be accessible, I just want to modify the site navigation menu.

I also need to get the image file from the first child image page to display in the link->data-filename.

What am I doing wrong or how can I modify this loop to include the first child page of each child?

<?php
$items = $pages->listed();
if($items->isNotEmpty()):
?>
  <?php foreach($items as $item): ?>
    <h3<?php e($item->isOpen(), ' class="active"') ?>><?= $item->title()->html() ?></h3>
      <?php
      $children = $item->children()->listed();
      if($children->isNotEmpty()):
      ?>
        <?php foreach($children as $child): ?>
        <h2><a class="swap"<?php e($child->isOpen(), ' class="active"') ?> href="<?= $child->$first()->url() ?>" data-filename="<?= $child->$first()->$file->url() ?>"><?= $child->title()->html() ?></a></h2>
        <?php endforeach ?>
      <?php endif ?>
  <?php endforeach ?>
<?php endif ?>

You cannot call variables as methods like $first() or $file() on an object, if these variables are not defined. The methods are called first() and file(), without the $ sign.

<?php
$items = $pages->listed();
if($items->isNotEmpty()):
?>
  <?php foreach($items as $item): ?>
    <h3<?php e($item->isOpen(), ' class="active"') ?>><?= $item->title()->html() ?></h3>
      <?php
      $children = $item->children()->listed();
      if($children->isNotEmpty()):
      ?>
        <?php foreach($children as $child): ?>
          <?php if ($imagePage = $child->children()->first()) : ?>
            <h2><a class="swap"<?php e($child->isOpen(), ' class="active"') ?> href="<?= $imagePage->url() ?>" data-filename="<?= ($file = $imagePage->file()) ? $file->url() : '' ?>"><?= $child->title()->html() ?></a></h2>
          <?php endif ?>
        <?php endforeach ?>
      <?php endif ?>
  <?php endforeach ?>
<?php endif ?>

Thank you for your fast response! This worked perfectly and makes sense. It was a long day of staring at my screen, I appreciate your help!

1 Like