Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add redirects to WordPress posts using static HTML pages
/* 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";
$blog = rtrim($argv[1], '/');
$template = <<<HTML
<!DOCTYPE html>
<meta charset="utf-8">
<link rel="canonical" href="{{link}}">
<meta http-equiv="refresh" content="0; url={{link}}">
<a href="{{link}}">Click here if you are not redirected.</a>
$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));
$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