Use get_the_title()
since you’re already being passed a post ID.
function rename_attacment( $post_ID ) {
$post = get_post( $post_ID );
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
//dirname = File Path
//basename = Filename.Extension
//extension = Extension
//filename = Filename
$newfilename = get_the_title( $post_ID );
$newfile = $path['dirname'] . "https://wordpress.stackexchange.com/" . $newfilename . "." . $path['extension'];
rename( $file, $newfile );
update_attached_file( $post_ID, $newfile );
}
add_action( 'add_attachment', 'rename_attacment' );
I’m not sure this will work as you expect it to though. From my understanding, WordPress considers Attachments to be similar to Posts and Pages and will treat the name as duplicate.
For example, if you have a Page called Test
and you rename the attachment to Test
WordPress will realize that the title is a duplicate and change it to Test-1
so that it doesn’t confuse the two.