1

I am having an issue with my project that requires my media URLs to be unique. I have found that if a media item is uploaded, deleted, and reuploaded with the same name in the same month, then the URL for the media item is the same as the old item.

E.g.

  1. I upload an item named "pic.jpeg" and the URL is "myserver/wp-content/uploads/2022/08/pic.jpeg"
  2. I delete pic.jpeg from the Media Library
  3. I upload a different item named "pic.jpeg" and the URL is "myserver/wp-content/uploads/2022/08/pic.jpeg"

I need the second uploaded item to have a different URL from the first, even though it was deleted.

Is there a way I can make media URLs truly unique, by changing the default URL from the "year/mo/name" format to something different?

1 Answer 1

1

You could certainly change the upload folder structure using an upload_dir filter hook, but I think a more direct solution might be to append some other text to the end of the file name. I think an easy unique string could just be the current timestamp, and encoding it in hexadecimal would make it a little more compact.

I'm not too familiar with WordPress's media APIs, but it looks to me that the wp_handle_upload_prefilter and/or wp_handle_sideload_prefilter filter (depending on how you are performing the upload) would be reasonable place to implement this functionality:

function wpse408625_media_upload_append_ts( $file ) {
  $ext      = substr( $file['name'], strrpos( $file['name'], '.' ) );
  $filename = substr( $file['name'], 0, strlen( $file['name'] ) - strlen( $ext ) );

  $file[ 'name' ] = $filename . '-' . dechex( time() ) . $ext;

  return $file;
}

add_filter( 'wp_handle_upload_prefilter', 'wpse408625_media_upload_append_ts' );
add_filter( 'wp_handle_sideload_prefilter', 'wpse408625_media_upload_append_ts' );

The above should transform a filename such as pic.jpeg into one like pic-62faeadd.jpeg. As long as you don't manage to upload an image, delete it, then upload another with the same filename all within the span of one second, this should prevent future collisions!

3
  • This works great for uploading through the Media Library on the web, but I am uploading via the REST API. Do you know of a method for making this work in that situation? Aug 17, 2022 at 17:03
  • @HannahEstes it looks like an upload through the REST API might trigger either wp_handle_upload_prefilter or wp_handle_sideload_prefilter, depending on the specifics of the request. I've added the other to the answer - does that seem to work for your use-case?
    – bosco
    Aug 18, 2022 at 3:24
  • that worked! Thank you for your help Aug 18, 2022 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.