Here's the function I use for WP to rename images during upload on the fly and set the image's filename to match the post slug.

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);

I am trying to modify this function so that it's no longer limited to images only (in this particular case, for example, I want WP to rename both images and mp3's during upload), and can't get it to work.

Another issue with this function is that it only successfully renames attachments if the post was published prior to uploading attachments. WP autosaves posts almost immediately after filling out the post title field, the post slug is created at that moment, so why is publishing the post a necessary step? Would there be a way to modify this function to make it work with just autosave?

Thank you very much in advance for your help.

1 Answer 1


Simply decide this on what data you got for your file (I use $file instead of $arr as argument, as it's easier to understand later).

if ( 'image' == array_shift( explode( '/', $file['type'] ) ) )
    // do wonderful things

You can always simply look into what you got with adding the following line to your filter:

exit( printf( '<pre>%s</pre>', var_export( $file, true ) ) );

This will exit during the upload and stop the process, so you can inspect the output and see what data you got from your upload. Just do this for different file types and alter your code according to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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