Skip to main content
4 of 4
replaced http://wordpress.stackexchange.com/ with https://wordpress.stackexchange.com/

Rename file after title , one small 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