Last active
March 27, 2016 14:19
-
-
Save dala00/1f73dc93da60255553ea to your computer and use it in GitHub Desktop.
wordpressの各記事をはてなブログに301リダイレクトするRewriteRuleの作成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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