Add redirects to WordPress posts using static HTML pages
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 | |
/* This script can to be used when your replacing your WordPress site with | |
* a static site, while keeping your blog on WordPress. | |
* | |
* Make sure you increase the number of syndicated posts to include all posts | |
* in Settings > Reading on your WordPress blog. | |
*/ | |
if ($argc < 2) { | |
echo "USAGE: php {$argv[0]} BLOG_URL\n"; | |
exit(100); | |
} | |
$blog = rtrim($argv[1], '/'); | |
$template = <<<HTML | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Redirecting...</title> | |
<link rel="canonical" href="{{link}}"> | |
<meta http-equiv="refresh" content="0; url={{link}}"> | |
</head> | |
<body> | |
<h1>Redirecting...</h1> | |
<a href="{{link}}">Click here if you are not redirected.</a> | |
<script>location='{{link}}'</script> | |
</body> | |
</html> | |
HTML; | |
$curl = curl_init($blog . '/feed/'); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($curl, CURLOPT_FAILONERROR, true); | |
$response = curl_exec($curl); | |
if (!$response) { | |
fwrite(STDERR, curl_error($curl)); | |
exit(1); | |
} | |
$feed = simplexml_load_string($response); | |
foreach ($feed->channel->item as $item) { | |
$link = $item->link; | |
$path = ltrim(parse_url($link, PHP_URL_PATH), '/'); | |
$dir = substr($path, -1) === '/' ? $path : dirname($path); | |
$file = substr($path, -1) === '/' ? 'index.html' : basename($path); | |
if (!file_exists($dir)) mkdir($dir, 0755, true); | |
if (!file_exists($dir . $file)) { | |
$html = strtr($template, ['{{link}}' => $link]); | |
file_put_contents($dir . $file, $html); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment