October CMS resources and help articles

Simple and to the point. Optimized by the community.

Use the original filename as thumbnail name

8
by OFFLINE, last modified on September 1st, 2019

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,
    ];
}

Discussion

2 comments

1
alxy
Post on August 31st, 2019 8:43 PM

The getThumbFilename method is now public. That means, this snippet needs to be updated.

0
OFFLINE
Post on September 1st, 2019 9:25 AM
We use cookies to measure the performance of this website. Do you want to accept these cookies?