カスタム投稿タイプを使用時、投稿のスラッグに数字を入れないと投稿ページが表示されない。
WordPressでfunctions.phpに記載をし、カスタム投稿タイプ(information)を作成しました。
また、カスタムタクソノミーにてカテゴリー(information_cat)を作成。
パーマリンク設定はプラグインの「Custom Post Type Permalinks」を使用し、
/%information_cat%/%postname%/
に設定をしています。
(カスタマイズされたカスタムタクソノミーのパーマリンクを使用する。と
カスタムタクソノミーのアーカイブに、 post_type クエリーを追加。は
チェックをつけていません。)
記事投稿画面から、スラッグを手動で入力し設定をしている状況です。
現状
投稿のスラッグを「test01」にすると表示される
サイトurl/information/news/test01
投稿のスラッグを「test」にすると表示されない
サイトurl/information/news/test
実現したいこと
投稿のスラッグに数字を入れなくても表示されるようにしたい。
発生している問題・エラーメッセージ
サイトurl/information/news/test
にアクセスするとトップページに飛びます。
該当のソースコード
functions.php
php
1// カスタム投稿タイプ(お知らせ) 2function cpt_register_information() { 3 $labels = [ 4 "singular_name" => "information", 5 "edit_item" => "information", 6 ]; 7 $args = [ 8 "label" => "お知らせ", 9 "labels" => $labels, 10 "description" => "", 11 "public" => true, 12 "show_in_rest" => true, 13 "rest_base" => "", 14 "rest_controller_class" => "WP_REST_Posts_Controller", 15 "has_archive" => true, 16 "delete_with_user" => false, 17 "exclude_from_search" => false, 18 "map_meta_cap" => true, 19 "hierarchical" => true, 20 "rewrite" => [ "slug" => "information", "with_front" => false ], 21 "query_var" => true, 22 "menu_position" => 5, 23 "supports" => [ "title", "editor", "thumbnail" ], 24 ]; 25 26 register_taxonomy( 27 'information_cat', 28 'information', 29 array( 30 'hierarchical' => true, 31 'update_count_callback' => '_update_post_term_count', 32 'label' => 'お知らせのカテゴリー', 33 'search_items' => 'カテゴリを検索', 34 'all_items' => 'すべてのカテゴリ', 35 'public' => true, 36 'show_ui' => true, 37 'show_in_rest' => true, 38 'meta_box_cb' => 'post_categories_meta_box', 39 ) 40 ); 41 42 register_post_type( "information", $args ); 43} 44add_action( 'init', 'cpt_register_information' ); 45 46 47 48/***************************************** 49カスタム投稿タイプのカテゴリーのアーカイブ 50*****************************************/ 51function add_custom_rewrite_rules() { 52 add_rewrite_rule('information/([^0-9]+)/?$', 'index.php?information_cat=$matches[1]&taxonomy=information_cat', 'top'); 53 add_rewrite_rule('information/([^0-9]+)/page/([^/]+)/?$', 'index.php?information_cat=$matches[1]&taxonomy=information_cat&paged=$matches[2]', 'top'); 54} 55add_action('init', 'add_custom_rewrite_rules');
試したこと
register_taxonomyでカスタムタクソノミーを作らずに、register_post_type内で
'taxonomies' => array('category')
でやってみると、投稿のスラッグに数字を入れなくても表示されましたが、今度はカテゴリーアーカイブページが表示されなくなってしまいました。
(既存の「投稿」のカテゴリーとの関係かと思っています…)
何かアドバイスをいただけますと嬉しいです。
よろしくお願いいたします。
あなたの回答
tips
プレビュー