Use the original filename as thumbnail name
8
If you want to replace the generated thumb_6_800_0_0_0_auto.jpg
filenames with more SEO-friendly variants like the-original-file-name_6_800_0_0_0_auto.jpg
then follow the steps below:
Add the following class to your plugin:
<?php namespace YourVendor\YourPlugin\Models;
/**
* Custom thumbnail name attachment.
*
* @see https://octobertricks.com/tricks/use-original-filename-thumbnail-name
*/
class File extends \System\Models\File
{
/**
* Generates a thumbnail filename using the original filename.
* @return string
*/
public function getThumbFilename($width, $height, $options)
{
$original = parent::getThumbFilename($width, $height, $options);
$newName = str_slug(pathinfo($this->file_name, PATHINFO_FILENAME));
return str_replace('thumb_', $newName . '_', $original);
}
/**
* Generates a disk name from the supplied file name.
*/
protected function getDiskName()
{
$ext = strtolower($this->getExtension());
$name = str_slug(pathinfo($this->file_name, PATHINFO_FILENAME));
// A filename has to be at least 9 characters long.
if (strlen($name) < 9) {
$name .= str_random(9 - strlen($name));
}
return implode('.', array_filter([$name, $ext]));
}
}
Now simply use this model instead of System\Models\File
when you define attachMany
or attachOne
relationship.
<?php namespace YourVendor\YourPlugin\Models;
class Event extends Model
{
public $attachOne = [
'image' => \YourVendor\YourPlugin\Models\File::class,
];
}
The
getThumbFilename
method is now public. That means, this snippet needs to be updated.The trick has been updated! Thanks @alxy.
https://github.com/octoberrain/meta/commit/6a29266d4c87f4bff3b2c381563e9bce7ec51555