オーバースペックな重めプラグインを導入するのは避けようってんで、業務でよく使っていた「Custom post type UI」および「Yoast SEO」には頼らず、カスタム投稿タイプを追加してパンくずも調整する。
パンくず出力は、単機能のプラグインである「Breadcrumb Block」を使用。一応自力でも作れはするだろうけれど、ブロックに書き出すまでは面倒臭そうで、やる気が出なかった。
固定ページ「IT技術(information-technology)」とカスタム投稿タイプ「IT技術(post_it)」を作り、固定ページをカスタム投稿タイプの一覧ページとする。
「https://kariwatashi.info/information-technology(※1)/slug(※2)」って感じになって欲しいんすよね。
(※1)固定ページ
(※2)カスタム投稿タイプ記事
固定ページと投稿タイプのslugが被ると問題が発生するんで、投稿タイプのslugは別名を付けておいて、URLの書き出しの時に何とかする。
アーカイブは無効にする(固定ページが役を担うので)。そして、URL上の表示は固定ページのslugと同一に書き換える。
function add_custom_post() {
register_post_type(
'post_it',
array(
'label' => 'IT技術',
'public' => true,
'has_archive' => false,
'show_in_rest' => true,
'menu_position' => 21,
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'thumbnail',
'revisions',
'excerpt',
'custom-fields',
'page-attributes'
),
'rewrite' => array(
'slug' => 'information-technology',
'with_front' => false
)
)
);
}
add_action('init', 'add_custom_post');この段階でURL的には既にOKなのだけれど、何せアーカイブを無しにしているから、パンくず系のプラグインが道中に一覧ページを挟んでくれない。
そのため、何とか表示を整えねばならない。
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
if(is_plugin_active('breadcrumb-block/breadcrumb-block.php')){
add_action( 'breadcrumb_block_single_prepend', function ( $post, $breadcrumbs_instance ) {
$page_slug = '';
if ( 'post_it' === $post->post_type ){
$page_slug = 'information-technology';
}
$page_obj = get_page_by_path($page_slug);
if ( $page_obj ) {
$page_id = $page_obj->ID;
$breadcrumbs_instance->add_item( get_the_title( $page_id ), get_permalink( $page_id ) );
}
}, 10, 2 );
}同じ様な処理がいっぱいあるなら、もうちょっと効率的な書き方にした方がよさそう。