Blog / WordPress/ Two Methods to Automatically Rename Uploaded Media Files in WordPress

Two Methods to Automatically Rename Uploaded Media Files in WordPress

WordPress两种方法实现上传媒体图片文件自动重命名

Introduction

When publishing articles, we often need to upload media files like images and audio. WordPress does not automatically rename newly uploaded files by default, and manually renaming each file is tedious. How can we implement automatic renaming for uploaded media files?

This article presents two reliable methods to automatically rename uploaded files in WordPress for your reference.

Method 1: Rename by Upload Timestamp

This method generates a unique filename by obtaining the current timestamp and adding a random number, effectively preventing filename conflicts.

// WordPress upload file rename - based on timestamp
function git_upload_filter($file) {
    // Generate timestamp in YYYYMMDDHHMMSS format
    $time = date("YmdHis");
    // Combine new filename: timestamp + random number (1-100) + original extension
    $file['name'] = $time . "_" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
    return $file;
}
// Apply this filter during the upload pre-processing stage
add_filter('wp_handle_upload_prefilter', 'git_upload_filter');

Explanation: The original code concatenated the timestamp and random number directly, which could reduce readability. An underscore _ has been added as a separator to make filenames clearer (e.g., 20231015143045_78.jpg).

Method 2: Rename Using MD5 Hash

This method encrypts the original filename using MD5 and takes a portion of the hash as the new filename, generating a fixed-length unique name.

// WordPress upload file rename - based on MD5 hash
function rename_filename($filename) {
    $info = pathinfo($filename);
    // Safely get the file extension (corrected the 'emptyempty' error from original code)
    $ext = empty($info['extension']) ? '' : '.' . $info['extension'];
    // Get the original filename without extension
    $name = basename($filename, $ext);
    // MD5 encrypt the original filename, take the first 20 characters, then append the extension
    return substr(md5($name), 0, 20) . $ext;
}
// Apply this filter when WordPress sanitizes filenames
add_filter('sanitize_file_name', 'rename_filename', 10);

Explanation: Corrected the syntax error emptyempty to empty. This method completely changes the filename to a string like a3f8c72e1b9d0546a7b2.jpg, thoroughly avoiding issues that Chinese or special characters might cause, but it loses the readability of the original filename.

Usage and Important Notes

Choose either method above and add the corresponding code snippet to the end of your current theme's functions.php file to activate it.

Important Notes:

  • Choose One: Do not add both code snippets simultaneously, as this may cause conflicts or unpredictable results.
  • Backup: It is recommended to back up your theme files before making modifications.
  • Child Theme: If you are using a child theme, add the code to the child theme's functions.php to prevent modifications from being overwritten during theme updates.
  • Scope: After adding the code, it only applies to newly uploaded files. Existing files in the media library will not be renamed.

Post a Comment

Your email will not be published. Required fields are marked with *.