Media PHP Beginner

Clean Up File Names on Upload

Turn uploaded file names like "Café Menu FINAL (2).JPG" into clean, lowercase, URL-safe names like "cafe-menu-final-2.jpg".

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 12 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Only new uploads are renamed. Existing files and their URLs aren’t changed.
  • WordPress still adds -1, -2 and so on when a name already exists.

How to test it

Upload a file called Test Image Ünïcode (1).PNG. It should be saved as test-image-unicode-1.png.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only