Created
September 30, 2011 15:02
-
-
Save miya0001/1254007 to your computer and use it in GitHub Desktop.
WPに任意のURLを追加するためのクラス
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 | |
if (!class_exists('WP_AddRewriteRules')): | |
class WP_AddRewriteRules{ | |
private $rule = null; | |
private $query = null; | |
private $callback = null; | |
function __construct($rule, $query, $callback) | |
{ | |
$this->rule = $rule; | |
$this->query = $query; | |
$this->callback = $callback; | |
add_filter('query_vars', array(&$this, 'query_vars')); | |
add_action( | |
'generate_rewrite_rules', | |
array(&$this, 'generate_rewrite_rules') | |
); | |
add_action('wp', array(&$this, 'wp')); | |
} | |
public function generate_rewrite_rules($wp_rewrite) | |
{ | |
$new_rules[$this->rule] = $wp_rewrite->index . '?' . ( | |
strpos($this->query, '=') === FALSE | |
? $this->query . '=1' | |
: $this->query | |
); | |
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules; | |
} | |
private function parse_query($query) | |
{ | |
$query = explode('&', $query); | |
$query = explode( | |
'=', | |
is_array($query) && isset($query[0]) ? $query[0] : $query | |
); | |
return (is_array($query) && isset($query[0]) ? $query[0] : $query); | |
} | |
public function query_vars($vars) | |
{ | |
$vars[] = $this->parse_query($this->query); | |
return $vars; | |
} | |
public function wp() | |
{ | |
if (get_query_var($this->parse_query($this->query))) { | |
call_user_func($this->callback); | |
} | |
} | |
} | |
endif; | |
// eol |
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 | |
// 例 | |
// プラグイン有効化時にリライトルールをクリアする。 | |
register_activation_hook(__FILE__, 'flush_rewrite_rules'); | |
new WP_AddRewriteRules( | |
'mystyle.css$', | |
'mystyle', | |
'callback_function' | |
); | |
// 指定されたURLでアクセスがあった際に実行されるコールバック | |
function callback_function() | |
{ | |
header('Content-type: text/css; charset=UTF-8'); | |
echo 'body {background-color: #ff0000}'; | |
exit; // exitがないと続けてwp本体の処理が行われてしまう。 | |
} | |
コンストラクタでflushを登録せずにAddRewriteRules->flush()みたいなメソッドを用意するだけにしよう。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
別プラグインでこのやり方にツッコミが入ったけど意味がわかりませぬ。
the rewrite flush happens BEFORE init, which is a big no-no according to the WordPress Codex. By flushing the rewrites before init, the rewrites for custom post types are not being generated and permalinks to these pages are broken. In a normal configuration the problem can be easily solved by going to the Permalinks page of the settings and by clicking on update.