WordPressのカスタム投稿タイプを作成した際に、パーマリンクを投稿IDに設定したい場合があります。
その時に、ググると必ずと言っていいほど同じものがでるので、そのコードを使ってたのですが、使い回すようにするためにプラグイン化を行ったときに複数に分けて実行させてたのですね。
以下のコードが出回っているコードなのですが(CLASS化してるので若干違います。)
post_type.php
// 一部抜粋
// 若干手を加えてあります。
public function __construnct()
{
add_action('init', array(__CLASS__, 'rewrite'));
add_filter('post_type_link', array(__CLASS__, 'permalink'), 10, 2);
}
public static function rewrite()
{
global $wp_rewrite;
$post_type = self::POST_TYPE;
$query = "post_type=$post_type&p=";
$wp_rewrite->add_rewrite_tag("%{$post_type}_id%", '([^/]+)', $query);
$wp_rewrite->add_permastruct($post_type, "/$post_type/%{$post_type}_id%", false);
}
public static function permalink($post_link, $post)
{
global $wp_rewrite;
if (is_wp_error($post))
return $post;
if ($post->post_type === self::POST_TYPE)
{
$newlink = $wp_rewrite->get_extra_permastruct(self::POST_TYPE);
$newlink = str_replace("%".self::POST_TYPE."_id%", $post->ID, $newlink);
$newlink = home_url(user_trailingslashit($newlink));
return $newlink;
}
return $post_link;
}
さて、このコードのどこが問題になっているのかというと、別に問題はないのです。
じゃあ何が悪いのさということですが、フィルターフックが1つ足りないんです。
post_type_link
をフックした場合、post_link
も一緒にフックしてあげないと、どれか一つしか動かないということ。
複数の投稿タイプを別々で処理してる場合は、この点を注意しておけば、発狂しないで済む。。。
post_type.php
public function __construnct()
{
add_action('init', array(__CLASS__, 'rewrite'));
add_filter('post_type_link', array(__CLASS__, 'permalink'), 10, 2);
add_filter('post_link', array(__CLASS__, 'permalink'), 10, 2);
}
上記のように、フックを追加すれば、バグから解放されます。
寝る時間が無くなったのは、手を抜いた罰ということですね(・ω・`)