Last active
March 15, 2024 10:00
-
-
Save medienbaecker/439f8b0a14c2c11546181bc00b4ce202 to your computer and use it in GitHub Desktop.
Generate all thumbnails with Kirby CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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