Skip to content

Instantly share code, notes, and snippets.

@torounit
Last active August 29, 2015 14:10
Show Gist options
  • Save torounit/cc07f9683e4933deb95b to your computer and use it in GitHub Desktop.
Save torounit/cc07f9683e4933deb95b to your computer and use it in GitHub Desktop.
WordPressの固定ページの中身をテーマ内のファイルと片方向で同期する。

テーマ内の"page-contents"というディレクトリに、"固定ページのスラッグ.php"という名前があったとき、ファイルのほうが新しければ、WordPressの投稿データを更新します。 子ページの場合は、"parent_child.php"という名前にしておけば、"parent/child"が更新されます。

固定ページにHTMLをごりごり書いたり、それを検索とかにも使うなんて場合とかは有用かもしれないです。

毎回走らせると重いので、GETパラメーターとか、Cronで適当なタイミングで更新させるのがBetterかと思います。

<?php
Class PageContents {
private $dir;
private $separator = "_";
private $content_dir = "page-contents";
public function __construct() {
$this->dir = get_stylesheet_directory()."/".$this->content_dir;
}
private function getContentFiles() {
return array_map(function($fileName){
return $fileName;
}, glob($this->dir.'/{*.php}',GLOB_BRACE));
}
public function sync() {
foreach ($this->getContentFiles() as $key => $fileName) {
$pageName = str_replace([".php", $this->dir."/"], "", $fileName);
$pageName = str_replace([$this->separator], "/", $pageName);
$post = get_page_by_path($pageName);
if($post) {
if( strtotime($post->post_modified_gmt) < intval(filemtime($fileName)) ) {
$content = file_get_contents($fileName);
$post->post_content = $content;
wp_update_post($post);
}
}
}
}
}
<?php
add_action( "init", function(){
if(isset($_GET["sync"]) and $_GET["sync"] == "true"){
$pageContents = new WP\PageContents();
$pageContents->sync();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment