I’d like to rename files during upload and set their names to the post slug the files are being attached to, plus some random characters (a simple incremental counter will de just fine) to make the filenames different.
In other words, if I’m uploading/attaching images to the post whose page slug is “test-page-slug”, I’d like for the images to be renamed on the fly to test-page-slug-[C].[extension]
:
- test-page-slug-1.jpg
- test-page-slug-2.jpg
- etc, it doesn’t matter what the original filenames were.
There’s this plugin, Custom Upload Dir:
With this plugin you can construct paths from additional variables like: post title, ID, category, post author, post date and much more.
How can I do the same to filenames?
You’ll want to hook in to the wp_handle_upload_prefilter filter (which I can’t find any documentation on, but seems pretty simple). I’ve tried this out locally, and it seems to work for me:
In my testing, it seems like posts only have a slug if you have pretty permalinks enabled, so I’ve added a check to make sure there is a slug before renaming the file. You’ll also want to consider checking the file type, which I haven’t done here–I’ve just assumed it’s a jpg.
EDIT
As requested in the comment, this additional function alters some of the meta attributes for the uploaded image. Doesn’t appear to let you set the ALT text though, and for some reason the value you set as the “caption” is actually assigned as the description. You’ll have to monkey with it. I found this filter in the function wp_read_image_metadata(), which is located in wp-admin/includes/image.php. It’s what the media upload and wp_generate_attachment_metadata functions rely on to pull metadata from the image. You can take a look there if you want some more insight.
Edited 04/04/2012 to pull post ID from the REQUEST obj rather than checking the GET and POST successively. Based on suggestions in the comments.