Rename uploaded files in WordPress
Here is a function used in my free WordPress plugin User Submitted Posts that enables you to rename WordPress media uploads. So for example, if the user uploads a JPG image named “sweet-ride.jpg”, the following function will append a random string to rename the file “sweet-ride-random.jpg”, where “random” is a random alphanumeric string containing 20 characters. And it’s all made possible (and stupidly easy) thanks to the WordPress sanitize_file_name
filter hook.
Rename uploaded files
Here is the function to rename uploaded files in WordPress:
function shapeSpace_maybe_append_random($filename) {
$random = substr(str_shuffle('1234567890abcefghijklmnopqrstuvwxyz'), 0, 20);
$append = apply_filters('usp_file_append_random', true, $filename, $random);
if (!$append) return $filename;
$info = pathinfo($filename);
$ext = (isset($info['extension']) && !empty($info['extension'])) ? '.'. $info['extension'] : '';
$name = basename($filename, $ext) .'_'. $random;
return $name . $ext;
}
add_filter('sanitize_file_name', 'shapeSpace_maybe_append_random', 10);
As written, this function:
- Defines a random string
- Filters the string as needed
- Gets the file name via
pathinfo()
- Appends and returns the random string
- Hooks into WordPress via
sanitize_file_name
That’s the basic idea. No changes are necessary for this to work, but you may want to change the appended string as desired for your specific implementation.
Bonus: Version Control
Update! Here is an enhanced version of the above code that provides some basic version control for media assets:
function append_media_timestamp($filename) {
$timestamp = time(); // epoch time | formatted date >> date("YmdGs")
$append = apply_filters('usp_file_append_random', true, $filename, $random);
if (!$append) return $filename;
$info = pathinfo($filename);
$ext = (isset($info['extension']) && !empty($info['extension'])) ? '.'. $info['extension'] : '';
$name = basename($filename, $ext) .'-'. $timestamp;
return $name . $ext;
}
add_filter('sanitize_file_name', 'append_media_timestamp', 10);
This modified code improves the script’s cache-busting functionality by changing the random variable to a timestamp. Thanks to Joe Campbell for the updated code :)