Subcategories Use Their Parent Category's Template
Makes subcategories use the parent category's custom template, such as category-news.php or a "category-news" block template, when they do not have their own.
Opens WPIDE on
Code
// Templates for categories and other hierarchical taxonomies fall back to the parent term's template:
// /category/news/local/ uses category-news.php (or the category-news block template) when there is no category-local one.
foreach ( array( 'category', 'taxonomy' ) as $wpide_tpl_type ) {
add_filter( $wpide_tpl_type . '_template_hierarchy', function ( $templates ) {
$term = get_queried_object();
if ( ! $term instanceof WP_Term || ! $term->parent || ! is_taxonomy_hierarchical( $term->taxonomy ) ) {
return $templates;
}
$prefix = 'category' === $term->taxonomy ? 'category-' : 'taxonomy-' . $term->taxonomy . '-';
$extra = array();
foreach ( get_ancestors( $term->term_id, $term->taxonomy, 'taxonomy' ) as $ancestor_id ) {
$ancestor = get_term( $ancestor_id, $term->taxonomy );
if ( $ancestor && ! is_wp_error( $ancestor ) ) {
$extra[] = $prefix . rawurldecode( $ancestor->slug ) . '.php';
$extra[] = $prefix . $ancestor->term_id . '.php';
}
}
// Right after the term's own templates, before the generic ones.
$own = array( $prefix . rawurldecode( $term->slug ) . '.php', $prefix . $term->slug . '.php', $prefix . $term->term_id . '.php' );
$pos = 0;
foreach ( $templates as $i => $file ) {
if ( in_array( $file, $own, true ) ) {
$pos = $i + 1;
}
}
array_splice( $templates, $pos, 0, $extra );
return array_values( array_unique( $templates ) );
} );
}
Notes
Also works for hierarchical custom taxonomies; the subcategory's own template still wins when it exists.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.