Rename files on upload

no need to use a custom table, use an option, and the add_attachment hook:

function wpa59168_rename_attachment( $post_ID ) {

    $post = get_post( $post_ID );
    $file = get_attached_file( $post_ID );
    $path = pathinfo( $file );

    $count = get_option( 'wpa59168_counter', 1 );

    // change to $new_name = $count; if you want just the count as filename
    $new_name = $path['filename'] . '_' . $count;
    $new_file = $path['dirname'] . "https://wordpress.stackexchange.com/" . $new_name . '.' . $path['extension'];
    rename( $file, $new_file );    
    update_attached_file( $post_ID, $new_file );

    update_option( 'wpa59168_counter', $count + 1 );

}
add_action( 'add_attachment', 'wpa59168_rename_attachment' );

Leave a Comment