WordPress Logo Dark Mode

WordPress file upload capabilities have really improved over the years, but there’s one problem we keep running into — the filenames are perfectly preserved when you upload, which leaves to inconsistent and really long image file paths.

And to make matters worse, if you’re using Skitch to capture screenshots of various terminal commands, it captures the full path from Terminal and uses that as the file name, which is just absurdly long.

The much simpler solution is to simply add a couple of lines of code to change all uploaded images to a simple randomized file name, and then trim it down to the first 8 characters to make sure that image paths in the HTML aren’t too crazy.

// randomize upload filenames 
function htg_randomize_uploaded_filename( $filename ) {

	// does it have an extension? grab it
    $ext  = empty( pathinfo( $filename )['extension'] ) ? '' : '.' . pathinfo( $filename )['extension'];

    // return the first 8 characters of the MD5 hash of the name, along with the extension
    return substr(md5($filename), 0, 8) . $ext;

add_filter( 'sanitize_file_name', 'htg_randomize_uploaded_filename', 10 );

Paste the code into your functions.php file, located in your theme folder, and it should immediately start working.

This works by adding a function to the sanitize_file_name filter that does the work and returns the new file name. WordPress will attempt to use that new name – but if there’s a clash, it’ll add a -1 to the end and continue with numbering until it doesn’t have a clash anymore. Realistically that’s unlikely to happen, but it’s good to know that it won’t be an issue.

Profile Photo for Lowell Heddings Lowell Heddings
Lowell is the founder and CEO of How-To Geek. He’s been running the show since creating the site back in 2006. Over the last decade, Lowell has personally written more than 1000 articles which have been viewed by over 250 million people. Prior to starting How-To Geek, Lowell spent 15 years working in IT doing consulting, cybersecurity, database management, and programming work.
Read Full Bio »