Importing Jekyll Posts into WordPress

Nearly four years ago I switched my main site over to Jekyll. It’s been great. But late last year I decided to make that site and its blog purely about my software business and move all of my non-work posts over to my tyler.io domain so I could have a personal site again. To encourage myself to write more, I built the site with WordPress so it would be easy to publish. That meant I needed a way to convert and import all of my old Jekyll Markdown posts into WordPress. I found a few scripts that exported WordPress into Jekyll, but not the other way around. So I hacked together my own script, which I’ve pasted below. Hopefully this will help anyone wanting to make the same transition.

The script takes a directory of Markdown posts in the following format, reads their header meta-data, and imports them into your WordPress database.

date: 2013-04-08 20:57:14
title: PebbleCam
layout: post
permalink: /blog/2013/04/pebblecam/index.html
slug: pebblecam
Post content...

<?PHP
require '/path/to/markdown-extra.php';
$db = mysql_connect('localhost', 'root', 'password') or die(mysql_error());
mysql_select_db('tylerio', $db) or die(mysql_error());
$files = scandir('posts');
array_shift($files); // .
array_shift($files); // ..
foreach($files as $fn)
{
import_md($fn);
}
function import_md($fn)
{
global $db;
$md = file_get_contents('posts/' . $fn);
$lines = explode("\n", $md);
$dashes = array_shift($lines);
$tmp = explode(':', array_shift($lines));
$date = $tmp[1] . ':' . $tmp[2] . ':' . $tmp[3];
$date = date('Y-m-d H:i:s', strtotime($date));
$title = trim(array_pop(explode(':', array_shift($lines))));
$layout = array_shift($lines);
$permalink = trim(array_pop(explode(':', array_shift($lines))));
$slug = trim(array_pop(explode(':', array_shift($lines))));
$dashes = array_shift($lines);
$body = implode("\n", $lines);
$body = str_replace('{{ site.cdn_url }}', 'http://cdn.clickontyler.com', $body);
$title = mysql_escape_string($title);
$body_md = mysql_escape_string($body);
$body_html = mysql_escape_string(Markdown($body));
$permalink = str_replace('index.html', '', $permalink);
echo $permalink . ' ' . 'http://tyler.io/blog' . $permalink . "\n";
$sql = "INSERT INTO wp_posts (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_status, comment_status, ping_status, post_name, post_modified, post_modified_gmt, post_parent, post_type) VALUES ";
$sql .= "(1, '$date', '$date', '$body_html', '$body_md', '$title', 'publish', 'closed', 'open', '$slug', '$date', '$date', 0, 'post')";
mysql_query($sql, $db);
$id = mysql_insert_id($db);
mysql_query("UPDATE wp_posts SET guid = 'http://tyler.io/?p=$id' WHERE ID = $id", $db);
mysql_query("INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES ($id, '_sd_is_markdown', '1')", $db);
}