Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
Where do I include this script in my WordPress install? Should I make it a plugin or do I add this to a functions file? I want to work automatically or know how to enable it so it does all the magic of changing the name automatically for me. Thanks! –  user22720 Oct 20 '12 at 20:23

1 Answer 1

up vote 9 down vote accepted

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:

function wpsx_5505_modify_uploaded_file_names($arr) {

    // Get the parent post ID, if there is one
    if( isset($_REQUEST['post_id']) ) {
        $post_id = $_REQUEST['post_id'];
    } else {
        $post_id = false;
    }

    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if($post_id && is_numeric($post_id)) {

        // Get the post slug
        $post_obj = get_post($post_id); 
        $post_slug = $post_obj->post_name;

        // If we found a slug
        if($post_slug) {

            $random_number = rand(10000,99999);
            $arr['name'] = $post_slug . '-' . $random_number . '.jpg';

        }

    }

    return $arr;

}
add_filter('wp_handle_upload_prefilter', 'wpsx_5505_modify_uploaded_file_names', 1, 1);

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.

function wpsx_5505_modify_uploaded_file_meta($meta, $file, $sourceImageType) {

    // Get the parent post ID, if there is one
    if( isset($_REQUEST['post_id']) ) {
        $post_id = $_REQUEST['post_id'];
    } else {
        $post_id = false;
    }

    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if($post_id && is_numeric($post_id)) {

        // Get the post title
        $post_title = get_the_title($post_id);

        // If we found a title
        if($post_title) {

            $meta['title'] = $post_title;
            $meta['caption'] = $post_title;

        }

    }

    return $meta;

}
add_filter('wp_read_image_metadata', 'wpsx_5505_modify_uploaded_file_meta', 1, 3);

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.

share|improve this answer
    
MathSmath, I can't believe this totally works, thank you so much! Do you think we could extend it a little bit further and make it assign title and alt (both the same) to the uploaded images based on the name of the post we're attaching them to? :) That would be just perfect. Thank you ever so much for your help! –  pereyra Dec 16 '10 at 23:29
    
@pereyra Glad it worked! I've updated my answer to include another function for altering some of the image meta data. I couldn't get it to set the alt text, but it does set the image title to the post title. –  MathSmath Dec 17 '10 at 16:20
    
@pereyra Also, please put a checkmark beside the answer so that people know it's resolved. High five! –  MathSmath Dec 17 '10 at 16:21
    
This works, thank you! Actually I have found that as long as the title field is filled out, WP will use the same value for both alt and title, unless the alt field is given a different value, so just $meta['title'] = $post_title; is perfect for my needs. Again, thank you so much for your help. –  pereyra Dec 17 '10 at 19:23
    
This no longer works, $_GET variables are empty. –  ThomasReggi Aug 30 '11 at 9:31

protected by Community Mar 31 '13 at 2:20

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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