phpforeachkirby

Fatal error: Call to a member function url() on a non-object on line 8


I am new to PHP, currently getting error saying

Fatal error: Call to a member function url() on a non-object on line 8

Below is the code I am trying

<?php
   $subpages = $site->pages()->children()->visible();
   $image_url = $subpages->image()->url();
   $title = $subpage->title()->text();

   foreach($subpages as $subpage) {
      echo '<div class="col-md-4">';
      echo '<h2>' . $title . '</h2>';
      echo '<a href="' . $subpage->url() . '" title="' . $title . '">';
      echo '<img src="' . $image_url . '" alt="' . $title . '" class="img-responsive img-thumbnail">';
      echo '</a>';
      echo '</div>';
   }
?>

Solution

  • Here's your code corrected:

    <?php
       $subpages = $site->children()->visible();
       foreach($subpages as $subpage) {
       $image_url = $subpage->image()->url();
       $title = $subpage->title()->html();
          echo '<div class="col-md-4">';
          echo '<h2>' . $title . '</h2>';
          echo '<a href="' . $subpage->url() . '" title="' . $title . '">';
          echo '<img src="' . $image_url . '" alt="' . $title . '" class="img-responsive img-thumbnail">';
          echo '</a>';
          echo '</div>';
       }
    ?>
    

    What's wrong with your code: