Rename existing WordPress Attachments files, titles

If you change your website name, or you have to change some strings in existing imagedata of your website, we need to do the following steps:

Step 1: Fetch all attachments

Step 2: Rename all corresponding uploaded files

Step 3: update attachment data so that new files would be recognized by WP

Step 4: Update title, description data as well.

Here is a snippet which implements all 4 steps above.

function eh_rename_old_attachments($find,$replace){
    $images=get_posts(['post_type'=>'attachment','posts_per_page'=>100000]);
    foreach($images as $image){
        if(strpos($image->post_name,$find)!==false){
            $file = get_attached_file($image->ID);  
            $path = pathinfo($file);
            
            $newfile = str_replace($find,$replace,$file);
            rename($file, $newfile); 
            update_attached_file( $image->ID, $newfile );

            $newpost=[];
            $newpost['ID']=$image->ID;
            $newpost['post_title']=str_replace($find,$replace,$image->post_title);
            $newpost['post_name']=str_replace($find,$replace,$image->post_name);
            $newpost['post_content']=str_replace($find,$replace,$image->post_content);
            $newpost['guid']=str_replace($find,$replace,$image->guid);
            $newpost['post_title']=str_replace($find,$replace,$image->post_title);            
            wp_update_post($newpost);               
            echo $newfile.' has been renamed! '.PHP_EOL;
        }
    }
}

eh_rename_old_attachments();

The script renames not only the attachment file itself, but also does the needed replacement in image title, description.

Get more useful WP tricks and snippets by subscribing to my mailclub.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.