Last active
June 13, 2016 06:05
-
-
Save nuex/ca1c5cdf8c49ab8a425ea8b3c66b8122 to your computer and use it in GitHub Desktop.
Sync a directory of static html pages with Wordpress
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 | |
$dir = '/var/www/html'; | |
if (getenv('WORDPRESS_PATH')) { | |
$dir = getenv('WORDPRESS_PATH'); | |
} | |
require_once($dir . '/wp-load.php'); | |
class PageSync | |
{ | |
public static function export() { | |
$pages = get_pages(); | |
foreach ($pages as $page) { | |
self::export_page($page); | |
} | |
} | |
public static function import() { | |
$dir = new DirectoryIterator(getenv('SYNC_PATH')); | |
foreach ($dir as $fileinfo) { | |
if (!$fileinfo->isDot()) { | |
self::import_page($fileinfo); | |
} | |
} | |
} | |
private static function export_page($page) { | |
$filename = $page->post_name . '.html'; | |
$target = getenv('SYNC_PATH') . '/' . $filename; | |
$file = fopen($target, 'w'); | |
fwrite($file, $page->post_content); | |
fclose($file); | |
} | |
private static function import_page($fileinfo) { | |
$name = $fileinfo->getBasename('.' . $fileinfo->getExtension()); | |
$pages = get_posts(['name' => $name, 'post_type' => 'page', | |
'posts_per_page' => 1, 'caller_get_posts' => 1]); | |
if (!empty($pages)) { | |
$file = fopen($fileinfo->getPathname(), 'r'); | |
$contents = fread($file, filesize($fileinfo->getPathname())); | |
fclose($file); | |
$page = $pages[0]; | |
wp_update_post(['ID' => $page->ID, 'post_content' => $contents]); | |
} | |
} | |
} | |
class PageSyncCli | |
{ | |
public static function run($args) { | |
if (!isset($args[1])) { | |
self::fail(); | |
} | |
$action = $args[1]; | |
if ($action == 'export') { | |
PageSync::export(); | |
} else if ($action == 'import') { | |
PageSync::import(); | |
} else { | |
self::fail(); | |
} | |
} | |
public static function fail() { | |
$usage = "usage: php page-sync.php [import|export]\n"; | |
die($usage); | |
} | |
} | |
PageSyncCli::run($argv); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment