Force sub-categories to use the parent category template

A couple of times in the last several years, I’ve needed sub-categories to inherit their parent’s archive template, but it’s just not something the Template Hierarchy supports. I’ve seen several plugins that tried and failed to do it, so finally I wrote a little filter that in my testing, works any number of levels deep, from sub-sub-categories to sub-sub-sub-categories. Enjoy!

</p>
<p>function new_subcategory_hierarchy() {<br />
	$category = get_queried_object();</p>
<p>	$parent_id = $category-&gt;category_parent;</p>
<p>	$templates = array();</p>
<p>	if ( $parent_id == 0 ) {<br />
		// Use default values from get_category_template()<br />
		$templates[] = &quot;category-{$category-&gt;slug}.php&quot;;<br />
		$templates[] = &quot;category-{$category-&gt;term_id}.php&quot;;<br />
		$templates[] = 'category.php';<br />
	} else {<br />
		// Create replacement $templates array<br />
		$parent = get_category( $parent_id );</p>
<p>		// Current first<br />
		$templates[] = &quot;category-{$category-&gt;slug}.php&quot;;<br />
		$templates[] = &quot;category-{$category-&gt;term_id}.php&quot;;</p>
<p>		// Parent second<br />
		$templates[] = &quot;category-{$parent-&gt;slug}.php&quot;;<br />
		$templates[] = &quot;category-{$parent-&gt;term_id}.php&quot;;<br />
		$templates[] = 'category.php';<br />
	}<br />
	return locate_template( $templates );<br />
}</p>
<p>add_filter( 'category_template', 'new_subcategory_hierarchy' );</p>
<p>