Blog

【WordPress】親カテゴリーのテンプレートを子カテゴリーにも適用する方法

2013.10.21 2020.10.25 WordPress

WordPressでは、カテゴリーごとにテンプレートファイルを用意することで、それぞれに個別のテンプレートを適用することができます。

しかしその場合、カテゴリーごとにひとつずつテンプレートファイルを用意しなくてはならず、子カテゴリーに親カテゴリーと同じテンプレートを使用したい場合(結構多いはず)には、それぞれのテンプレートファイルを別々に用意しなくてはなりません。

そういった場合に、子カテゴリー用のテンプレートファイルを用意しなくても、子カテゴリーに親カテゴリーのテンプレートファイルを適用する方法。

親カテゴリーのテンプレートを子カテゴリーにも適用する方法

function.phpに下記ソースを追加します。

function.php
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//親カテゴリーのテンプレートを子カテゴリーに適用

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;
}