Migrating image links in WordPress database

2010.05.05

I have been wanting to migrate the blog from kosertech.com/blog to the root of my domain at kosertech.com.  When I first installed wordpress it wasn’t something I thought I could build out a whole site with and I didn’t think it was really mature enough to rely on.  I had visions of building out a static site in the root of my domain and then leveraging wordpress for ongoing updates.

I think wordpress has come a long way since I originally installed it so I made the move over the last couple of days.  The only issue that was a little tricky to resolve was that all my uploaded images in old posts pointed to the old directory kosertech.com/blog/wp-content/uploads which is a problem as I wanted to do away with that directory since I was migrating everything from inside the blog directory up one level.

I did some digging in the wordpress database and determined that the post content is in the wp_posts table in the post_content column.  The basic job to do is find all occurences of “http://www.kosertech.com/blog/” and replace them with “http://www.kosertech.com/”.  I did some digging and found the REPLACE command that is basically like a string replace from most programming languages.  You supply it the source text (in this case the post_content database column), the text to replace and the replacement text and it goes to work.

You can wrap this all up into the following query replacing my urls with your own and run this directly against MySQL via command line client or through a utility such as phpMyAdmin.

UPDATE wp_posts SET post_content =

REPLACE( post_content, ‘http://www.kosertech.com/blog/’ , ‘http://www.kosertech.com/’);

That query should return the number of rows that we’re updated.  I recommend copying your wp_posts table to a temporary copy and trying the updated on the copy first, and as always backup your database prior to trying any of these things.

Categories : tips  tools

Leave a comment