Rename files during upload using variables

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.

Leave a Comment