In WordPress, when users upload attachments (such as images or documents) with Chinese filenames, the default sanitize_file_name function converts them to pinyin or removes Chinese characters. This can make file URLs difficult to recognize. Sometimes, you may want to preserve the Chinese title displayed in the Media Library while renaming the actual file stored on the server (e.g., using a timestamp + random number) to avoid potential encoding issues and conflicts.
Solution: Custom Filename Handling Function
Using WordPress's sanitize_file_name filter, you can customize the renaming logic for uploaded attachments. The following example function automatically renames files to a "year-month-day-hour-minute-second + random number.extension" format during upload, without affecting the title displayed in the Media Library.
// WordPress: Auto-rename uploaded files without changing attachment title
function wp_custom_sanitize_file_name( $filename ) {
// Get current time in YmdHis format
$time = date("YmdHis");
// Generate random number between 1000 and 9999
$random = mt_rand(1000, 9999);
// Get file extension
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Combine new filename: time_random.extension
return $time . "_" . $random . "." . $extension;
}
add_filter( 'sanitize_file_name', 'wp_custom_sanitize_file_name', 10, 1 );
Code Explanation
- Function Purpose: This function hooks into the
sanitize_file_namefilter to process filenames during upload. - Filename Generation: The new filename consists of three parts: current time down to seconds (e.g., 20231015143022), an underscore, a 4-digit random number, and the original file extension. Example:
20231015143022_1234.jpg. - Title Preservation: This function only modifies the physical filename stored on the server; it does not affect metadata like "Title" or "Caption" in the WordPress Media Library. You can still set and retain Chinese titles for attachments.
- Benefits: Avoids server compatibility issues and URL encoding problems with Chinese filenames, while ensuring uniqueness through timestamp and random number to prevent overwrites.
Usage Instructions
- Add the code above to the end of your current theme's
functions.phpfile, or via a custom plugin. - After saving, newly uploaded attachments will be automatically renamed according to the new rule.
- Note: This change only applies to future uploads; existing filenames will not be modified.
Extensions and Considerations
- Custom Naming Rules: You can modify the logic inside
wp_custom_sanitize_file_nameas needed, such as using user ID or post ID as part of the filename. - SEO Considerations: Renaming images to meaningless strings may not be ideal for image SEO. If SEO is a priority, consider more complex solutions like converting Chinese titles to English keywords for filenames.
- Debugging: If issues occur after upload, check server permissions for writing new filenames and ensure there are no syntax errors in the code.