Check if page exists

This is perhaps an obvious question, but I can’t seem to figure out how to check if a page exists using the $site->find() function and a string inserted by the user.

So for example I try to do this:

<?php if($site->find('artists/'.$name)): ?>
   <p><?php echo $site->find('artists/'.$name)->title(); ?></p>
<?php endif; ?>

The echo does work when the page exists. What doesn’t work is that when the searched page doesn’t exist, the if doesn’t prevent the whole site from crashing.

I also tried

if($site->find('artists/'.$name)->count() > 0):

to no success.


What kind of error message do you get? The code is perfectly ok and should work, only thing I could image is that $name is not a string, but then the positive case shouldn’t work either …

From my understanding of site()->find() uses a page’s UID and not a page’s path.

If the find() fuction traverses through pages & subpages, this should work.

<?php if($site->find($name)): ?>

<?php echo $site->find($name)->title(); ?>

<?php endif; ?> ```

Nevermind what I said, @texnixe is right, $site->find() only works for top level pages.

$site->find() only finds pages on the main level, not any page whatever the depth, so using find with the path works, at least in my installations. There might be differences depending on Kirby version, though.

Error is:

Call to a member function url() on a non-object


My mistake. I had a similar code just above this which was returning the same error. I didn’t realize the code was twice on the page, sorry. I added the same if clause I proposed in my first reply and it prevents the fatal error. So, yes, like @texnixe predicted, this code is perfectly ok:

<?php if($site->find('artists/'.$name)): ?>
   <p><?php echo $site->find('artists/'.$name)->title(); ?></p>
<?php endif; ?> 

Note: How does it work here, shall I delete this threat?

1 Like

You have already marked it as “Solved”, so I would leave it at that.