Fixing image attachments in Wordpress with no postmeta data

The scenario:
For whatever reason you have imported images into a wordpress blog from a different blog or an older version of the same blog.  

You copy the new image files into the uploads folder.   Now you know this isn’t enough to make images appear in Wordpress as images are related to database entries.

With this in mind you copy accross all the post entries in the wp_posts table that have a guid field value that matches the images you want to get working.

However still things don’t work correctly.  Symptoms include no thumbnails working in the Wordpress admin system for the images and all the image related functions within Wordpress that you may be using in your theme fail.   

I spent a few hours at a total loss as to why all the useful WP image retreival functions (such as wp_get_attachment_image() ) were returning empty string results.

The cause:
The most likely cause of images not working in this kind of situation is that meta data for the images hasn’t been entered or is incorrect.  Wordpress adds entries to two tables for each image uploaded.   So as well as the entry in wp_posts you should find multiple meta data entries for each image in the wp_postmeta table.

This data is in a really specific form, so how on earth are you going to get that in place to make the images work properly? 

The solution:

fixWPImageMetaData() function - download it here! 

Well the answer is the following code!    A word of warning: this code is quite rough and full of debug that appears on screen, but that is deliberate so you can see whats going on. Good luck and remember to make a full site backup before you run this code, I will not be held responsible for further cockups to your data!

A huge thanks to Ross McKay for starting me on the right track with this, his original article can be found here:

created: 6/3/14
last updated: 7/3/14