TomPich Posted March 17, 2024 Posted March 17, 2024 Hello all, For my current project, each page have an image called thumbnail used for various purposes. If the thumbnail is not provided, I have a fallback image. So on almost each PHP template, I have the following code at the beginning: $thumbnailUrl = $page->pageThumbnail ? $page->pageThumbnail->size(1920, 400, ["crop" => "center"])->webp->url : $pages->get(1039)->configDefaultImage->url ; To avoid repeating that on each page PHP template, what can I do to generate, for each page, something like $page->thumbnailUrl automatically? Do I have to use a hook ? Thanks guys for your help Cheers Thomas
bernhard Posted March 17, 2024 Posted March 17, 2024 You can either use hooks: <?php $wire->addHookMethod("Page::thumbnail", function(HookEvent $event) { $event->return = ...; }); Or even better you use custom page classes (it's really easy thx to pw!) and there you create a DefaultPage class that adds your method: <?php namespace ProcessWire; class DefaultPage extends Page { public function thumbnail() { return ...; } } Then you just make sure that thumbnail() always returns a PageImage object and then in all your templates you can do this: echo $page->thumbnail()->size(100,100)->webp->url; And it will automatically render either the custom or the fallback image. Check out https://processwire.com/blog/posts/pw-3.0.152/#new-ability-to-specify-custom-page-classes for details 1
TomPich Posted March 17, 2024 Author Posted March 17, 2024 Thank you very much, Bernhard. This DefaultPage class will be very handy for a lot of stuff ! 1
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now