Skip to content

Instantly share code, notes, and snippets.

@medienbaecker
Last active March 15, 2024 10:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save medienbaecker/439f8b0a14c2c11546181bc00b4ce202 to your computer and use it in GitHub Desktop.
Save medienbaecker/439f8b0a14c2c11546181bc00b4ce202 to your computer and use it in GitHub Desktop.
Generate all thumbnails with Kirby CLI
<?php
declare(strict_types = 1);
set_time_limit(0);
use Kirby\CLI\CLI;
use Kirby\Toolkit\Dir;
use Kirby\Toolkit\Str;
use Kirby\Cms\Media;
return [
'description' => 'Generates all thumbnails',
'command' => static function (CLI $cli): void {
$kirby = $cli->kirby();
$cli->bold("Generating thumbnail jobs for all pages…");
foreach ($kirby->site()->index() as $page) {
$page->render();
$cli->out($page->url());
}
$cli->bold("Generating thumbnails…");
$generated = [];
foreach (Dir::index($kirby->root('media'), true) as $path) {
if (!Str::endsWith($path, '.json')) continue;
$parts = explode('/', $path);
$count = count($parts);
$type = $parts[0];
$hash = $parts[$count - 3];
$path = implode('/', array_splice($parts, 1, $count - 4));
$filename = str_replace('.json', '', array_pop($parts));
$generated[] = $path . '/' . $filename;
if ($type === 'assets') {
Media::thumb($path, $hash, $filename);
continue;
}
$model = match($type) {
'site' => $kirby->site(),
'users' => $kirby->user($path),
default => $kirby->page($path)
};
Media::link($model, $hash, $filename);
$cli->success($path . '/' . $filename . ' ✅');
}
if (count($generated)) {
$cli->success()->bold(count($generated) . ' thumbnails have been created' . ' ✅');
}
else {
$cli->success("Nothing to generate");
}
}
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment