カテゴリーテンプレートを親子で共有する
2020年12月25日
親子カテゴリーで共通のテンプレートを利用する方法は以前にも書いたが、すぐに忘れるのと今回はまたちょっと違う仕様で再度掲載。
functions.phpに以下を追加
//categoryテンプレート親子共有 newsページのカテゴリー欄
add_filter( 'category_template', 'parent_category_template' );
function parent_category_template( $template ) {
$category = get_queried_object();
if ( $category->parent != 0 &&
( $template == "" || strpos( $template, "category.php" ) !== false ) ) {
$templates = array();
while ( $category->parent ) {
$category = get_category( $category->parent );
if ( !isset( $category->slug ) ) break;
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
}
$templates[] = "category.php";
$template = locate_template( $templates );
}
return $template;
}
クライアントさんのnewsページのカテゴリー記事一覧のために使用。
newsの子カテゴリーの表示が他のカテゴリーのテンプレートに行ってしまうのでこの仕様を追加。