ここはちょっと見せられない

ぜったいぜったい見せられない

category一覧もsingle投稿も、親カテゴリのテンプレートを使いたい

コピペ用に置いとく。 functions.php にこれを入れておけば良い。覚書。

Wordpressの関数使ったほうがいいんかなと思って書いた。

これで、 category-(term slug).php single-(term slug).php を使ってくれるようになる。

見ればわかると思うけど、投稿(singleのほう)は登録カテゴリの中で最初に出てくるものを採用してる。 もし、yoastSEO使っててメインカテゴリが取得できるならそれを使ったら良いと思う。運用次第。

<?php
function get_template_for_category( $template ) {
    $term = get_queried_object();
    $ancestors = get_ancestors($term->term_id, 'category');
    $term = get_category(array_pop($ancestors));
    $slug_template = locate_template( "category-{$term->slug}.php" );
    if ( $slug_template ) { return $slug_template; }
    return $template;
}
add_filter( 'category_template', 'get_template_for_category' );

function get_template_for_single( $template ) {
    $post = get_queried_object();
    $term = get_the_category($post->ID);
    $ancestors = get_ancestors($term[0]->term_id, 'category');
    $term = get_category(array_pop($ancestors));
    $slug_template = locate_template( "single-{$term->slug}.php" );
    if ( $slug_template ) { return $slug_template; }
    return $template;
}
add_filter( 'single_template', 'get_template_for_single' );