Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.