How to Randomize Uploaded Filenames in WordPress

By Lowell Heddings on August 2nd, 2017

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, here on HTG Pro I’m using Skitch to capture screenshots of various terminal commands, and 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.