Wordpress - Change attachment filename

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

}

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.


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.

Tags:

Attachments