Roman
October 17, 2019, 5:48pm
1
Hi, I am using this model to have cover image from files section:
class BlogpostPage extends Page
{
public function cover()
{
return $this->content()->get('cover')->toFile() ?? $this->image();
}
}
As I understand, it’s taking file, that is first by filename, but maybe it’s possible to show the one, that is first by sort order?
You can use the following to get the first file:
class BlogpostPage extends Page {
public function cover() {
if($this->hasImages()) {
return $this->images()->sortBy('sort', 'asc')->first();
}
}
}
(untested)
I tend to use a page method plugin for stuff like that as it’s not bound to one template/model:
Kirby::plugin('my/methods', [
'pageMethods' => [
'cover' => function() {
if($this->hasImages()) {
return $this->images()->sortBy('sort', 'asc')->first();
}
}
]
]
1 Like
Roman
October 17, 2019, 6:18pm
3
Checked the first one, working fine, thank you! Also checked second, fixed some syntax errors, but still seems not to work.
Roman
October 17, 2019, 6:23pm
4
Also tried adding “cover” field (in case editor wants to override first image and choose custom cover image), it’s still showing first image, is it possible to show what is in cover field, if it’s not empty?
Yes:
class BlogpostPage extends Page {
public function cover() {
return $this->content()->get('cover')->toFile() ?? $this->images()->sortBy('sort', 'asc')->first();
}
}
<?php if ($cover = $page->cover()): ?>
<?= $cover ?>
<??php endif ?>
Note that a page method won’t override a page model, so adding a page method with the same name as an existing page model method won’t have any effect (at least not on pages that use the model).
1 Like
Roman
October 17, 2019, 6:29pm
6
Ah, I see, understand now, perfect, thank you! So now it’s showing first image from files section, or cover, if it’s selected, very nice.