How to fetch subpages from a different page

How do you fetch content from subpages in different page that your code is in?

For example, I’m trying to fetch content from subpages in the “testimonials” page to show up on my home page.

Here’s the code, which is obviously giving me errors:

<?php $tesitmonial = $site->page('testimonials')->children()->find('aaron-valenty'); ?>
      
        <div class="testimonial__container sml med--col-6 med--offset-1 xlrg--col-6 xlrg--offset-3">

            <img src="<?php echo $testimonial->image()->toFile['url'] ?>" alt="<?php echo $testimonial->image()->toFile['alt'] ?>" class="testimonial__image">

            <div class="testimonial__client">
                <h5 class="testinomial__client-name"><?php echo $testimonial->title ?></h5>

                <h5 class="testimonial__client-site">
                  <?php if($testimonial->site-link() != ''): ?>
                    <a href="<?php echo $testimonial->site-link ?>" class="testimonial__client-link" target="_blank"><?php echo $testimonial->site ?></a>
                  <?php else: ?>

                    <?php echo $testimonial->site ?>

                  <?php endif ?>
                </h5>

            </div>
        </div>
    <?php endif; ?>

There’s a typo on the variable assignment, it should be $testimonial instead of $tesitmonial.

<?php $tesitmonial = $site->page('testimonials')->children()->find('aaron-valenty'); ?>

I recommend that you enable debug mode on your development environment to spot errors like this more easily: c::set('debug', true)

1 Like

This should be

 <?php if($testimonial->site_link() != ''): ?>

And these two commands

$testimonial->image()->toFile['url'] 
$testimonial->image()->toFile['alt']

will not work either. You can’t use array syntax with an object. And the image() method will already give you a file object, so that does not make sense. What do you want to get here? An image from a field or the first image in the folder?

It should be

$image = $testimonial->image() //to get the first image in the folder
$image = $testimonial->fieldname()->toFile() //to get an image from a field and make it into a file object
if($image) {
  echo $image->url();
}

In this line the parenthesis are missing after title:

<h5 class="testinomial__client-name"><?php echo $testimonial->title ?></h5>

Here as well, but what are you trying to do here? BTW. there’s a typo in the class name as well, so you will wonder why your styles don’t work as expected.

  <?php echo $testimonial->site ?>

Also, before calling a method like url() on a file object, check if the image exists first.

1 Like