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 );


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'] . "/" . $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.

  • Thanks for your answer Howdy , I try the code like this and with some tweaks and don't work but i find a plugin that renames directly uploaded file , with date and post title but post title don't work so i take a look on plugin and i think this code has some problems ? if(isset($fileRenamingOptions['post_title_renaming'])){ $postSlug = $this->getPostSlug(); if($postSlug!=''){ $finalFileName = $postSlug; } } Maybe this function is deprecated ..old , i don't know – I.Alex Mar 21 '16 at 17:22
  • ahh btw the plugin is no longer updated from 2 years .. so i can't speak with author. – I.Alex Mar 21 '16 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.