Skip to content

Instantly share code, notes, and snippets.

@dala00
Last active March 27, 2016 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dala00/1f73dc93da60255553ea to your computer and use it in GitHub Desktop.
Save dala00/1f73dc93da60255553ea to your computer and use it in GitHub Desktop.
wordpressの各記事をはてなブログに301リダイレクトするRewriteRuleの作成
<?php
$hatenaId = 'hatenaId';
$apiKey = 'apiKey';
$host = 'hostname of blog';
$auth = "$hatenaId:$apiKey";
require 'wp-config.php';
$pdo = new PDO(
'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
DB_USER,
DB_PASSWORD,
array(PDO::ATTR_EMULATE_PREPARES => false)
);
$pdo->query('SET NAMES ' . DB_CHARSET);
$stmt = $pdo->query("SELECT * FROM wp_posts WHERE post_status = 'publish'");
$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$posts[$row['post_title']] = $row['ID'];
}
$xml = file_get_contents("https://$auth@blog.hatena.ne.jp/$hatenaId/$host/atom/entry");
$entry = new SimpleXMLElement($xml);
header('Contents-type: text/html;charset=utf-8');
echo '<pre>';
while ($entry && $entry->entry) {
foreach ($entry->entry as $row) {
$title = (string)$row->title;
$newLink = getLink($row->link, 'alternate');
if (isset($posts[$title])) {
echo 'RewriteCond %{QUERY_STRING} p=' . $posts[$title] . '$' . "\n";
echo 'RewriteRule ^$ ' . "$newLink? [R=301,L]\n";
}
}
sleep(1);
$next = getLink($entry->link, 'next');
$entry = null;
if ($next) {
$url = str_replace('//', "//$auth@", $next);
$xml = file_get_contents($url);
$entry = new SimpleXMLElement($xml);
}
}
function getLink($links, $rel) {
foreach ($links as $link) {
if ($link->attributes()->rel == $rel) {
return $link->attributes()->href;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment