カテゴリーとその子カテゴリには、特別なテンプレートを適用する

WordPressでは、category-slug.php category-id.php テンプレートを作る事で、指定したカテゴリのプレゼンテーションを変更することが出来ます。

ただ、カテゴリが階層構造になっている場合、子カテゴリには、親のテンプレートは適用されません。親カテゴリ、子カテゴリのグループを対象に、特別なテンプレートを適用していく道を、探してみました。

以下のコードは、カテゴリID41とその子カテゴリの場合に、index.phpテンプレートを適用します。

<?php
add_filter( 'template_include', 'my_interrupt_template' );

function my_interrupt_template( $template) {
	
	$args= array(
	'type' => 'post',
	'child_of' => 41,
	);	
	$ids= array( $args['child_of'] );
	$categories= get_categories( $args );
	
	if( isset( $categories ) &amp;&amp; !empty( $categories ) ) {
		foreach ( $categories as $category ) {

			$ids[]= absint( $category->term_id );
		}
	}

	if ( is_category( $ids ) ) {
		//この例では、indexテンプレートを呼び出しています。
		return get_index_template();
	}	
	return $template;	
}
?>
[emulsion_relate_posts]