When uploading images, many people consider renaming the file names. Whether for SEO optimization or for easier management, this is a common practice. We start by discussing a basic logic for uploading images with renamed files, gradually delving into more complex scenarios and examining if renaming is truly beneficial.
Initial Requirement
Imagine the following scenario: while uploading images, we want to rename each image file based on the upload timestamp to ensure file name uniqueness. Here’s the code to accomplish that:
function git_upload_filter($file) {
// Check if the uploaded file is an image type
$image_mime_types = array('image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp');
if (in_array($file['type'], $image_mime_types)) {
// If it's an image, rename it based on current timestamp
$time = date("YmdHis");
$file['name'] = $time . "_" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'git_upload_filter');
This code generates a unique file name for each image based on the current timestamp. While this ensures that file names won’t conflict, the names themselves lack meaningful context.
More Complex Requirement: Determining if a File Name Needs Renaming
As we explore this topic further, various types of image upload scenarios arise. We might want to rename some “meaningless” file names while retaining “sensible” ones. For example:
Images generated by AI like MidJourney typically have file names that include random numbers, usernames, and meaningless strings, such as
12_username_A_cat_in_glasses_64f50acd-8bfe-4725-a647-4104a52b4806.png
. In this case, we should remove the nonsensical elements and retain only the descriptive parts of the image.Images pasted from the clipboard might have file names like
image_20240916_150938.png
. Although these lack specific meaning, they don’t necessarily require renaming.
Improved Solution
Here’s the refined code to address these requirements:
function git_upload_filter($file) {
// Check if the uploaded file is an image type
$image_mime_types = array('image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp');
if (in_array($file['type'], $image_mime_types)) {
// Extract file name and extension
$filename = pathinfo($file['name'], PATHINFO_FILENAME);
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
// Handle images generated by AI like MidJourney
if (preg_match('/^d+_[a-zA-Z0-9]+_(.+?)_[a-zA-Z0-9-]+(_d+)?$/', $filename, $matches)) {
// Extract and use