September 27, 2013

How to merge two databases in WordPress?

merge ahead

How to merge two databases in WordPress?

You must be surprised that what does it mean by merging two databases in WordPress and why it is required? In fact, i faced a challenge few days ago where new database was updated with respect to the settings, themes and other installation stuff but the old database was having genuine posts, drafts and even pages which were mistakenly not imported to the new copy of WordPress. So the challenge was to keep both copies but to make two databases work together was not practically easy and recommended. What i did, analyzed number of posts in both databases and found the old database posts in bulk. Simply renamed the two tables “posts and postmeta” from old DB and imported to the new database. Only two tables are imported to the new DB. Then run the following mysql query.

<?php
$e = mysql_query("
SELECT
p.*
FROM
wp_posts_old p
WHERE
post_status = 'publish'
");
if(mysql_num_rows($e)>0){
while($f=mysql_fetch_object($e)){
echo $f->ID.'<br>';
//INSERT INTO NEW DB AS A POST
}
}
?>

By this query, posts from the old DB is simply inserted to new DB. You can copy the uploads directory to the new DB as well.

Last updated: March 19, 2014