Thursday, August 20, 2015

WordPress - How to migrate media (attachment, gallery) properly (single or multisite)

One of the big problem when you migrate your WordPress blog to another server with a new domain name is the media gallery. What happened to me was even though I had already moved all the photos (media) to the new location but nothing showed up in the Media dashboard and all the gallery shortcode in posts were broken. I figured out earlier today that I need to update the media links or attachments attribute when I importing the old data (exported WXR file). Here is the step-by-step detail:

(I'm doing this for my multisite WordPress)

1. In the old WordPress: Export old blog data (Tools > Export > select All Content > press Download Export File). You will have a xml file.

2. Copy over all the photos from the old WordPress to the new one. For example:

Old: /var/www/oldblog/wp-content/blogs.dir/777/
New: /var/www/newblog/wp-content/uploads/sites/777/

3. Open the export file using a text editor. Search and replace the old media path with the new one. For example:

Old: http://old.mywordpress.com/myblog/
New: http://new.mywordpress.com/myblog/

and

Old: http://old.mywordpress.com/myblog/files/
New: http://new.mywordpress.com/myblog/wp-content/uploads/sites/777/

This will tell the importer download the photos from the new server instead (I copied all the upload folder over the new WordPress in step 2)

4. In the new server, install the Attachment Importer plugin.

5. Import your WXR file using the WordPress importer (Tools > Import > WordPress), but do not select the option to Download and Import Attachments.

6. Navigate to the Attachment Importer screen (Tools > Import Attachment Importer). Select your WXR export file. Select the user you would like to be the owner of the downloaded images. Default: current user. Sit back and let the importer run.

7. Using wp-cli to search and replace any old domain urls in wp_777_posts and wp_777_postmeta tables (777 is the new blog id):

/path/to/newblog/root/$ wp search-replace 'http://old.mywordpress.com/myblog/' 'http://new.mywordpress.com/myblog/' wp_777_posts wp_777_postmeta --url=http://new.mywordpress.com/myblog

Search again the wp_777_posts and wp_777_postmeta to make sure all the URL and guid are correct. If not, do the search-and-replace again.

8. Make sure the Upload Url Path setting is empty (network admin > site > edit the blog) (Network Admin > Site > Edit the blog > Settings)

All the photos and gallery should be displayed properly now! Awesome!!!!

References:
[0] https://wordpress.org/plugins/attachment-importer/
[1] http://wordpress.stackexchange.com/questions/67840/where-does-the-media-library-live-in-the-database/95683#95683