2021年09月29日
親カテゴリーのテンプレートを子カテゴリーに適用
functions.phpに追記
■特定のカテゴリーに適用したい場合
/* 親カテゴリーのテンプレートを子カテゴリーに適用 */
add_filter( 'category_template', 'my_category_template' );
add_filter( 'category_template', 'my_category_template' );
function my_category_template( $template ) {
$category = get_queried_object();
if ( $category->parent == カテゴリーID ) {
$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;
}
■すべてのカテゴリーに適用したい場合
add_filter( 'category_template', 'my_category_template' );
function my_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;
}