Skip to content

Instantly share code, notes, and snippets.

@miya0001
Created March 3, 2012 13:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miya0001/1966149 to your computer and use it in GitHub Desktop.
Save miya0001/1966149 to your computer and use it in GitHub Desktop.
WordPressに独自のページを表示する
<?php
if (!class_exists('WP_AddPage')):
class WP_AddPage {
private $rule = null;
private $title = null;
private $callback = null;
private $template = null;
private $filter = false;
function __construct($rule, $title, $callback)
{
if (!class_exists('WP_AddRewriteRules')) {
wp_die("Class WP_AddRewriteRules is not exists.");
}
$this->rule = $rule;
$this->title = $title;
$this->callback = $callback;
}
public function init()
{
new WP_AddRewriteRules(
$this->rule,
'custom-'.preg_replace('/\W/', '', $this->rule),
array(&$this, "_display")
);
}
public function set_filter($filter = false)
{
$this->filter = $filter;
return true;
}
public function set_template($template)
{
$this->template = $template;
return true;
}
public function _page_template($template)
{
return $this->template;
}
public function _display()
{
if ($this->template) {
add_filter('page_template', array(&$this, "_page_template"));
}
$content = call_user_func($this->callback);
if ($this->filter === false) {
global $wp_filter;
unset($wp_filter['the_content']);
}
global $wp_query;
$wp_query->is_404 = null;
$wp_query->is_page = null;
$wp_query->is_single = null;
$wp_query->is_singular = 1;
$wp_query->is_search = null;
$wp_query->is_archive = null;
$wp_query->is_date = null;
$wp_query->is_day = null;
$wp_query->is_home = null;
$wp_query->post_count = 1;
$wp_query->post->post_title = $this->title;
$wp_query->posts = array();
$wp_query->posts[0] = new stdClass();
$wp_query->posts[0]->ID = 0;
$wp_query->posts[0]->post_author = 1;
$wp_query->posts[0]->post_title = $this->title;
$wp_query->posts[0]->comment_status = 'close';
$wp_query->posts[0]->comment_count = 0;
$wp_query->posts[0]->ping_status = 'close';
$wp_query->posts[0]->post_type = 'custom-page';
$wp_query->posts[0]->post_status = 'publish';
$wp_query->posts[0]->post_parent = 0;
$wp_query->posts[0]->post_content = $content;
$wp_query->posts[0]->post_date = time();
}
}
endif;
// EOF
<?php
// 例 wpより前のフックで以下のようなコードを実行。
$cpanel = new WP_AddPage(
'cpanel$',
'コントロールパネル',
array(&$this, "cpanel")
);
// wp_contentフィルターを適用する場合はtrueをセットする。
$cpanel->set_filter(true);
// テーマファイル内にpage-cpanel.phpがあればそれを使用して表示する。
// デフォルトでは固定ページ用のテンプレート(page.php)
$cpanel->set_template("page-cpanel.php");
$cpanel->init(); // カスタムページを登録
function cpanel() {
// apiにアクセスしたりデータベースから値をとったり何でもござれ!
return "カスタムコンテンツ";
}
@miya0001
Copy link
Author

miya0001 commented Mar 3, 2012

以下のクラスも必要。
https://gist.github.com/1254007

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment