LoginSignup
10
8

More than 5 years have passed since last update.

カスタム投稿のリンク生成を変更する際の注意点

Posted at

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);
}

上記のように、フックを追加すれば、バグから解放されます。

寝る時間が無くなったのは、手を抜いた罰ということですね(・ω・`)

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8