Jump to content

Automaticaly create a page field from existing fields


TomPich
 Share

Recommended Posts

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

Link to comment
Share on other sites

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

  • Thanks 1
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...