I need to rename the raw file name from camera like DCM4819032.jpg or 2015-12-11-204213.jpg to more organized one like IMG_00015.jpg.

I figured I will use the attachment ID as the number in that name.

So far I found a way to change the file name before uploading, but no access to the upcoming ID.

add_filter("wp_handle_upload_prefilter", function ($file) {
  $file["name"] = "custom-name.jpg";
  return $file;
}, 1, 1);

Is there a way to know what ID this attachment going to have?


Found a way from this question, it works, but it disables image resizing, which is important in my case.

add_action("add_attachment", function($file_id) {
  $file = get_attached_file($file_id);
  $path = pathinfo($file);

  $newfile_name = "IMG_" . $file_id . "." . $path["extension"];  
  $newfile = $path["dirname"] . "/" . $newfile_name;

  rename($file, $newfile);
  update_attached_file($file_id, $newfile);

From the comments, it says "WordPress won't understand that a rename has happened", which might be the reason why the resizing isn't working.

  • 1
    Any particular reason for this? – Pieter Goosen Dec 13 '15 at 14:22
  • Because my client (a photographer that want his photo to be downloadable) won't bother changing the raw image name from camera like DCM859132.jpg, it would be better if the file name is 00015.jpg or IMG_00015.jpg – hrsetyono Dec 13 '15 at 14:28
  • 00015.jpg is not better than DCM859132.jpg for any reason I can think of. – s_ha_dum Dec 13 '15 at 14:52
  • @s_ha_dum well, it's bit tidier, and since my client won't write any post, the ID of each image will be in consecutive order. – hrsetyono Dec 13 '15 at 14:55
  • Given the way WordPress handles IDs, you images still won't be in consecutive order-- numerical order, but not consecutive. IDs just don't work that way. As for "tidy", maybe to humans but for SEO, indexing, anything like that it is meaningless. To get any real value your client would have to give the images proper names, or you'd have to work out a way to do so-- extract captions or EXIF data, or something. I'm just making these notes because (while I haven't double checked this) the upload/save/post creation sequence is going to make this tricky and you aren't going to gain much if anything. – s_ha_dum Dec 13 '15 at 15:01

You just complicating yourself here. If you want a sequential ID just store it in an option and increment its value with each new upload. There is a very slight possibility of a race condition which might result with two images having the names of IMG_N.png and IMG_N-2.png but it is not likely to happen at all in sites with only one author writing at a time.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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