Change attachment filename

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

Thanks!
Dennis

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

}

Method 2

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.

Method 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.

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x