Rename images on upload

Also, I’m not sure why, but I had to remove from the initial code $count++.

If the $page has already 2 $images, the new uploaded file was numbered 4 (instead of 3), and then next 5 etc…
Not sure why it was counting one image more then the ones I had.

So now I have the following code

// Auto rename photos

kirby()->hook('panel.file.upload', function($file) {

    $page = $file->page();
    $title = $page->title();
    $count = 0;
    $old_filename = $file->filename();
    
    try {
        $count = $page->images()->count();
        // $count++;
        // Add 0 before $count so that it is two digits
        $count = str_pad($count, 2, '0', STR_PAD_LEFT);
        $filename = $title . "-" . $count;
        if (strpos($old_filename, 'box') !== false) {
            $filename = $filename . "-box";
        }
        $file->rename($filename);
        echo 'The file has been renamed';
    } catch(Exception $e) {
        echo 'The file has been renamed';
        // optional reason: echo $e->getMessage();
    }

});
1 Like