I have found two alternative solutions:
Option 1. Rename Media file using post slug
Place this code in your functions.php. It will rename every media file you upload on a post, using the post slug + a random number:
function wpsx_5505_modify_uploaded_file_names($arr) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
// Only do this if we got the post ID--otherwise they're probably in
// the media section rather than uploading an image from a post.
if($post_id && is_numeric($post_id)) {
// Get the post slug
$post_obj = get_post($post_id);
$post_slug = $post_obj->post_name;
// If we found a slug
if($post_slug) {
$random_number = rand(10000,99999);
$arr['name'] = $post_slug . '-' . $random_number . '.jpg';
}
}
return $arr;
}
add_filter('wp_handle_upload_prefilter', 'wpsx_5505_modify_uploaded_file_names', 1, 1);
View Source
Option 2. Rename media file with random number
Place the following code on a text file, name it “hash-upload.php” and place it inside your plugins folder. Then active it as a plugin through the WP Plugins section.
<?php
/**
* Plugin Name: Hash Upload Filename
* Plugin URI: https://stackoverflow.com/questions/3259696
* Description: Rename uploaded files as the hash of their original.
* Version: 0.1
*/
/**
* Filter {@see sanitize_file_name()} and return an MD5 hash.
*
* @param string $filename
* @return string
*/
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
?>
View Source
After a few tests, both worked well on my site. I’m using option #1 right now.
Hope this could help.
Greetings!