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){
    foreach($images as $image){
            $file = get_attached_file($image->ID);  
            $path = pathinfo($file);
            $newfile = str_replace($find,$replace,$file);
            rename($file, $newfile); 
            update_attached_file( $image->ID, $newfile );

            echo $newfile.' has been renamed! '.PHP_EOL;


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.