Skip to content

Instantly share code, notes, and snippets.

@ww24
Created May 9, 2015 14:20
Show Gist options
  • Save ww24/3e58e891f36a7b229126 to your computer and use it in GitHub Desktop.
Save ww24/3e58e891f36a7b229126 to your computer and use it in GitHub Desktop.
WordPress migration tool
#!/usr/bin/env node
/**
* WordPress Image URL Migration Tool
*
*/
var from_url = "http://wordpress.local/";
var to_url = "http://example.com/wordpress/";
var cheerio = require("cheerio");
var path = require("path");
var fs = require("fs");
var filename = process.argv[2];
if (! filename) {
console.log("usage: migration.js filename");
process.exit(1);
}
var filepath = path.resolve(__dirname, filename);
var xml = fs.readFileSync(filepath, {encoding: "utf8"});
var $ = cheerio.load(xml, {
xmlMode: true
});
$("item").each(function () {
var $item = $(this);
$item.find("wp\\:postmeta").each(function () {
var data = "";
var match = null;
if ($(this).find("wp\\:meta_key").text() === "thememakers_portfolio") {
data = $(this).find("wp\\:meta_value").text();
match = data.match(/i:[0-9]+?;s:[0-9]+?:"([^]+?)";/g);
if (match) {
// console.log(data);
match = match.map(function (str, index) {
var res = str.match(/i:[0-9]+?;s:[0-9]+?:"([^]+?)";/);
var url = res[1].split(from_url).join(to_url);
return ["i:", index, ";s:", url.length, ":\"", url, "\";"].join("");
});
data = ["a:", match.length, ":{", match.join(""), "}"].join("");
// console.log(data);
}
data = "<![CDATA[" + data + "]]>";
$(this).find("wp\\:meta_value").html(data);
}
});
});
var xml = $.html();
fs.writeFileSync(filepath + ".new.xml", xml, {encoding: "utf8"});
@ww24
Copy link
Author

ww24 commented May 9, 2015

WordPress の機能で移行すると画像の URL が適切に処理されない、たちの悪いテンプレート用マイグレーションスクリプト。

WordPress のエクスポート機能で吐き出した portfolio のデータ (XML) を入力すると、移行先にインポートするデータに変換される。移行先にも移行元と全く同じディレクトリ構造で画像ファイルをアップロードする。

usage

npm install cheerio
./migration.js wordpress.portfolio.xml

※ Node.js v0.10 以降が必要

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment