Overwrite url() in page model

In Kirby 2 I often overwrote the ->url() method in a page model like this:

<?php
class SectionPage extends Page {
  public function url() {
    return $this->parent()->url() . '#' . $this->slug();
  }
}

I can’t get this to work in Kirby 3, though. Here’s the error I get:

Fatal error: Declaration of SectionPage::url() must be compatible with Kirby\Cms\Page::url($options = NULL)

What does “compatible” mean in this context?


<?php
class SectionPage extends Page {
  public function url($options = null): string {
    return $this->parent()->url() . '#' . $this->slug();
  }
}

Awesome, this works! Thank you, Sonja!

For anyone having pages inside a separate sections or modules container and stumbling over this thread, you can use this:

<?php

class SectionPage extends Page {
	public function url($options = null): string {
		return $this->parents()->filterBy("intendedTemplate", "!=", "sections")->first()->url() . '#' . $this->slug();
	}
}

You are welcome.

You always have to check out the original method’s parameters and return type hints when trying to overwrite native methods.

I currently have the same problem. I modified the starterkit to only show articles (in subfolders) that are inside the “home” folder. I added a model/home.php with the code above, but the url stays the same -> site.com/subfolder-from-site/home/slug-of-the-article.

model/home.php

<?php
    class HomePage extends Page {
        public function url($options = null): string {
        return $this->slug();
    }
}

templates/home.php

<?php foreach ($page->children()->listed()->sortBy('date', 'desc') as $article): ?>
    <article class="note">
    <header class="note-header">
        <a href="<?= $article->url() ?>">
         <?= $article->title() ?>
         <time><?= $article->date()->toDate('d F Y') ?></time>
    </a>
    </header>
    </article>
<?php endforeach ?>

The overwritten url() method only affects pages with the home template. If you want to overwrite the article urls, you need a model/article.php (depending on the name of your article template).

1 Like

Well, didn’t see this small detail. Now it works fine, thank you! :slight_smile: