1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WordPressのタクソノミーアーカイブのパーマリンクを変更する

Last updated at Posted at 2020-12-23

ワードプレスのテーマtwentytwentyoneを基盤に、タクソノミーのアーカイブページのパーマリンクからタクソノミー名を削除する実装を行ったので、備忘録的にこの記事を残す。

環境情報

PHP:version 7.3.12
WordPress:version 5.5.3
WPテーマ:twentytwentyone

ゴールの確認

カスタム投稿タイプでオリジナルのタクソノミーをカテゴリーのように使い、そのタクソノミーのアーカイブページをそれぞれ作成したい場合に起こる問題です。

※ポストタイプ名が topic 、タクソノミー名が topic_category 、ターム名が news で今回 news のアーカイブページを作りたい想定です。

今回のゴールはアーカイブページのリンクが /topic/news/ になることです。

カスタム投稿タイプ作成時の設定

register_post_type の args に入れる配列に以下の二つを指定します。
特に 'with_front' => false は忘れてはいけない!

functions.php
$args = array(
    'has_archive' => true,
    'rewrite' => array( 'with_front' => false )
);

プラグイン Custom Post Type Permalinks の導入

Custom Post Type Permalinks というプラグインをインストールし、管理画面->設定->パーマリンク設定から topic のパーマリンク設定を /%topic_category%/%post_id%/ または /%topic_category%/%postname%/ などにします。

そして忘れてはいけないのが、「カスタマイズされたカスタムタクソノミーのパーマリンクを使用する。」にチェックを入れることです!

この時点でデフォルトのパーマリンクが /topic/topic_category/news/ になっているはずです。

topic_category の部分を削除する

後は functions.php からリンク設定を行って、リライトで設定を書き換えれば完成です!

functions.php
// topic_category のアーカイブページのパーマリンクを変更する
function my_custom_post_type_permalinks_set($termlink, $term, $taxonomy){
    return str_replace('/'.$taxonomy.'/', '/', $termlink);
}
add_filter('term_link', 'my_custom_post_type_permalinks_set',11,3);
// ページネーションがある場合▽▽
add_rewrite_rule('topic/([^/]+)/?$', 'index.php?topic_category=$matches[1]', 'top');
add_rewrite_rule('topic/([^/]+)/page/([0-9]+)/?$', 'index.php?topic_category=$matches[1]&paged=$matches[2]', 'top');
// ページネーションがある場合△△
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?