So I used this function that allows me to change the literal filename in the directory on upload. But, it doesn’t actually change the filename, hence changing the slug to the ID when attaching to a post.
For example, I upload a file with the filename “Grumpy-Cat-Ate-Nemo”, it’ll change to ID “89” because of the function. But it doesn’t actually change the filename in the WordPress database, so it stay’s as “Grumpy-Cat-Ate-Nemo.png” on WordPress even when the file is renamed to the ID.
I want the attachment url of a post to be http://example.com/grumpy-cat/89, not http://example.com/grumpy-cat/Grumpy-Cat-Ate-Nemo
add_action('add_attachment', 'rename_attacment');
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 = $post_ID;
$newfile = $path['dirname']."/".$newfilename.".".$path['extension'];
rename($file, $newfile);
update_attached_file( $post_ID, $newfile );
}
The
add_attachment
action is called after the attachment has been named. If you only want to change the name of the attachment (and the slug), you don’t need to change the name of the file and can just replace the code insiderename_attachment
with a call towp_update_post
.