Turn uploaded file names like "Café Menu FINAL (2).JPG" into clean, lowercase, URL-safe names like "cafe-menu-final-2.jpg".
add_filter( 'sanitize_file_name', function ( string $filename ): string {
$info = pathinfo( $filename );
$ext = isset( $info['extension'] ) ? '.' . strtolower( $info['extension'] ) : '';
$name = $info['filename'] ?? $filename;
$name = remove_accents( $name );
$name = strtolower( $name );
$name = preg_replace( '/[^a-z0-9]+/', '-', $name );
$name = trim( $name, '-' );
return ( '' !== $name ? $name : 'file' ) . $ext;
}, 10 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
File names with spaces, capitals and accented letters end up in your image URLs as Caf%C3%A9-Menu-FINAL-2.JPG. They look messy, and some servers and CDNs treat upper and lower case differently, which breaks links after a migration. This snippet cleans names as files are uploaded.
WordPress passes every uploaded file name through sanitize_file_name. The snippet splits off the extension, then turns accented letters into plain ones with remove_accents(), lowercases everything and replaces any run of other characters with a single hyphen.
The extension is lowercased too, so .JPG becomes .jpg. If nothing is left of the name, it falls back to file.
-1, -2 and so on when a name already exists.Upload a file called Test Image Ünïcode (1).PNG. It should be saved as test-image-unicode-1.png.