Skip to content

Instantly share code, notes, and snippets.

@jasny
Created June 28, 2015 12:18
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 jasny/4f33d3096a5c7e9da9d6 to your computer and use it in GitHub Desktop.
Save jasny/4f33d3096a5c7e9da9d6 to your computer and use it in GitHub Desktop.
Add redirects to WordPress posts using static HTML pages
<?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