I am attempting to change the name format that WordPress uses to rename uploaded files. For example, when I upload an image with filename cat-picture.jpg
WordPress will create scaled versions and rename the filename to variations of cat-picture-{WIDTHxHEIGHT}.jpg
. Is there a way I am able to move this width & height attribute to the beginning of the filename so instead I get variations of {WIDTHxHEIGHT}-cat-picture.jpg
? So, in the context of this example, I’d like the filename to be renamed to 600x400-cat-picture.jpg
. Thoughts?
I’ve looked at this post and this post, but I am unable to come up with a working solution. Here’s my code:
add_filter( 'wp_handle_upload_prefilter', 'modify_uploaded_file_names', 20);
function modify_uploaded_file_names( $image ) {
// Get default name of uploaded file and set to variable
$imagename = $image['name'];
// Case switch for multiple file extensions
switch ( $image['type'] ) {
case 'image/jpeg' :
$suffix = 'jpg';
break;
case 'image/png' :
$suffix = 'png';
break;
case 'image/gif' :
$suffix = 'gif';
break;
}
// Get size of uploaded image and assign to variable
$imagesize = getimagesize($image);
// Re-structure uploaded image name
$image['name'] = "{$imagesize[0]}x{$imagesize[1]}-{$imagename}.{$suffix}";
return $image;
}
I’ve managed to do it with the filter
image_make_intermediate_size
.Probably all the
path/filename.extension
dismembering and remaking could be optimized or made in a single stroke fashion, but alas, I’ll let that to the reader: