12

Is there a function that allows me to change the filename of an attachment, based on the Attachment ID I have?

Thanks! Dennis

4 Answers 4

25
+25

This will allow you to rename an attachment as soon as its uploaded:

add_action('add_attachment', 'rename_attachment');
function rename_attachment($post_ID){

    $file = get_attached_file($post_ID);
    $path = pathinfo($file);
        //dirname   = File Path
        //basename  = Filename.Extension
        //extension = Extension
        //filename  = Filename

    $newfilename = "NEW FILE NAME HERE";
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

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

}
6
  • 1
    very precisely explained :) Commented Oct 11, 2011 at 5:01
  • uhm, I get this rename(): http wrapper does not support renaming
    – Bakaburg
    Commented Sep 5, 2013 at 21:51
  • There is a typo here. The function should be called rename_attachment.
    – Avishai
    Commented Dec 17, 2016 at 22:41
  • 1
    I think for clarity is better if you name $post_ID as $attach_ID or something similar, because it could be confused with the parent post ID, while it's meant to be the attachment ID. Good anwser :) Commented May 17, 2019 at 14:50
  • Please notice this doesn't change the attachment guid, so the code relying on the guid to get the image source for instance won't work. Although generally speaking you shouldn't change a post guid, in this situation could be wise to update the guid as well. Commented May 17, 2019 at 19:10
4

Use Cases

The function works for

  • Adding files
  • Updating files (yes, also for files that are already present)
  • Multiple files

No-Use Cases

It aborts for autosave jobs, performed by wordpress automagically or if the targeted file types or mime types are not met.

Goodies

You can set the file name, file types & mime types that you want to change inside the function before the foreach loop. The file gets the post ID and then the attachment ID appended, so you can safely upload and change multiple files at a time. This also cares about ordering the files by (first) post ID and (second) attachment ID.

function wpse30313_update_attachment_names($post_ID)
{
    // Abort if WP does an autosave 
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
        return;

    # >>>> SET
        // New file name:
        $new_file_name = "___";

        // Best would be to take the post name as file name instead of a custom title:
        # $post_data = get_post( $post_ID );
        # $new_file_name = $post_data->post_name;

        // The file types we want be changed:
        $allowed_types = array(
            'image'
        );

        // The mime types we want to be changed:
        $allowed_ext = array(
             'jpg'
            ,'jpeg'
            ,'gif'
            ,'png'
        );
    # <<<< SET

    // Appended by post ID for collision safety
    $new_file_name = "{$new_file_name}-{$post_ID}";

    // get all attached files
    $attachments = get_children( array( 
         'post_type'    => 'attachment'
        ,'post_parent'  => $post_ID
    ) );

    // Bulk updating attached file names
    foreach ( $attachments as $att )
    {
        $att_ID     = $att->ID;
        // Append attachment ID (collision safety)
        // Also allows sorting files by post & then attchment ID
        $new_name   = "{$new_file_name}-{$att_ID}";

        $mime_type  = explode( "/", get_post_mime_type( $att->ID ) );
        $file_type  = $mime_type[0];
        $mime_type  = $mime_type[1];

        // Skip file types we don't want to change
        if ( ! in_array( $file_type, $allowed_types ) )
            continue;
        // Skip mime types we don't want to change
        if ( ! in_array( $mime_type, $allowed_ext ) )
            continue;

        // Get current file info
        $file_path = get_attached_file( $att->ID );
        $path   = pathinfo( $file_path );
        $dir    = trailingslashit( $path['dirname'] );
        $ext    = $path['extension'];

        // Build final name
        $final  = "{$dir}{$new_name}.{$ext}";

        // Skip if the path was already changed on upload
        // If we don't set this, the function wouldn't work for older files
        if ( $file_path == $final )
            continue;

        // Update attachment-post meta info for file
        rename( $file_path, $final );
        update_attached_file( $att_ID, $final );
    }

    return;
}
add_action( 'add_attachment', 'wpse30313_update_attachment_names' );
add_action( 'edit_attachment', 'wpse30313_update_attachment_names' );

The function should be added to your functions.php file or (better) as a separate small plugin. Just add a plugin comment on top, upload it to the plugins folder and activate.

1
  • thank you for the detailed reply, i ran the code and it seemed to execute, but i'm not sure if it changed anything. Should it change the post_name or guid of the attachment object? Commented Feb 1, 2017 at 4:54
3

I'd use PHP's rename and the path to the file given by get_attached_file.

function rename_file( $post_id, $newname ) {
    $file = get_attached_file( $post_id );
    rename($file,dirname($file).$newname)
}

NOTE that this has been not tested and you should extreme precaution when working whith files. It probably needs changing for it to work but may be a good starting point. Hope this helps.

Let me know if it helps and I'll change the code to the actual working code.

1
  • 1
    This breaks WordPress's link to the file, since WordPress won't understand that a rename has happened.
    – user66
    Commented Oct 17, 2011 at 13:04
3
add_action('add_attachment', 'rename');
function rename($post_ID){

    $post = get_post($post_ID);
    $file = get_attached_file($post_ID);
    $path = pathinfo($file);
    $newfilename = "mynewfilename";
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

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

}

Reference http://codex.wordpress.org/Function_Reference/update_attached_file http://wordpress.org/tags/add_attachment

1
  • This breaks the thumbnail previews in the WP dashboard.
    – Drew Baker
    Commented Nov 23, 2020 at 16:22

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.