# this script is modified after the recipe provided at
# http://spindrop.us/2006/05/19/migrating-from-drupal-47-to-wordpress
#
# updated 2007/05/28 with the comment count updater script from
# http://www.brendanloy.com/2007/02/wordpress-21-upgrade-problems.html
#
# this assumes that both wordpress and drupal are in separate databases. The wordpress database is called "wordpress" and the Drupal database is called "drupalmigration"

# first, nuke previous content in wordpress database
use wordpress;
delete from wp_categories;
delete from wp_posts;     
delete from wp_post2cat;
delete from wp_comments;

# categories
INSERT INTO 
    wp_categories (cat_ID, cat_name, category_nicename, category_description, category_parent)
SELECT term_data.tid, name, name, description, parent 
FROM drupalmigration.term_data, drupalmigration.term_hierarchy 
WHERE term_data.tid=term_hierarchy.tid;

# posts
INSERT INTO 
    wp_posts (id, post_date, post_content, post_title, 
    post_excerpt, post_name, post_modified)
SELECT DISTINCT
    n.nid, FROM_UNIXTIME(created), body, n.title, 
    teaser, 
    REPLACE(REPLACE(REPLACE(REPLACE(LOWER(n.title),' ', '_'),'.', '_'),',', '_'),'+', '_'),
    FROM_UNIXTIME(changed) 
FROM drupalmigration.node n, drupalmigration.node_revisions r
WHERE n.vid = r.vid;

# category --> post relationships
INSERT INTO wp_post2cat (post_id,category_id) SELECT nid,tid FROM drupalmigration.term_node ;

# category count updating
UPDATE `wp_categories` SET `category_count` = (SELECT COUNT(`post_id`) FROM `wp_post2cat` WHERE `wp_categories`.`cat_ID` = `wp_post2cat`.`category_id`);

# comments
INSERT INTO 
    wp_comments 
    (comment_post_ID, comment_date, comment_content, comment_parent, comment_author, comment_author_email, comment_author_url)
SELECT 
    nid, FROM_UNIXTIME(timestamp), 
    comment, thread, name, mail, homepage
FROM drupalmigration.comments ;

# update comments count on wp_posts table
UPDATE `wp_posts` SET `comment_count` = (SELECT COUNT(`comment_post_id`) FROM `wp_comments` WHERE `wp_posts`.`id` = `wp_comments`.`comment_post_id`);

# fix post slugs. first we have to remove the duplicate _____ chars, then replace that with a single - char
UPDATE wp_posts set post_name = REPLACE(post_name, '__', '_');
UPDATE wp_posts set post_name = REPLACE(post_name, '__', '_');
UPDATE wp_posts set post_name = REPLACE(post_name, '__', '_');
UPDATE wp_posts set post_name = REPLACE(post_name, '__', '_');
UPDATE wp_posts set post_name = REPLACE(post_name, '_', '-');