Search code examples
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:

    • You should use $site->children() to list all children of the site See kirby docs
    • You're defining $image_url and $title before the foreach which is not correct. I moved them just at the beginning of the foreach loop. Also corrected image_url to use subpage instead of subpages.
    • You're using text() on your title. That doesn't exist, use either kirbytext() or html() depending on what you want to do. See the docs.