How to make media URLs Unique

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!

techhipbettruvabetnorabahisbahis forumutaraftarium24eduseduseduseduseduseduedusedueduedu