Skip to main content
2 of 4
deleted 20 characters in body
Howdy_McGee
  • 20.8k
  • 24
  • 91
  • 175

Rename file after title , one smile problem

I'm using this question: Change Attachment Filename which works but it has a problem.

He renames every file with FileNameToRename and it's same image. What I want to do is instead of FileNameToRename I want to rename it to the Post Title. Is that possible ?

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 = "FileNameToRename";
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

    rename($file, $newfile);    
    update_attached_file( $post_ID, $newfile );

}
I.Alex
  • 23
  • 1
  • 8