# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Archives](https://wpide.com/library/category/archive/)
- Tags: archives, templates, categories
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/subcategories-use-parent-template/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Subcategories Use Their Parent Category's Template" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
