Skip to content

Instantly share code, notes, and snippets.

@caralgar
Created December 27, 2016 08:50
Show Gist options
  • Save caralgar/136b0ddba98567f9038320bd12ab3c26 to your computer and use it in GitHub Desktop.
Save caralgar/136b0ddba98567f9038320bd12ab3c26 to your computer and use it in GitHub Desktop.
How to make child categories recognize parent's template on WordPress
/*
Credits: http://wordpress.stackexchange.com/questions/145805/how-to-make-child-categories-recognize-parents-template-displays
*/
function new_subcategory_hierarchy() {
$category = get_queried_object();
$parent_id = $category->category_parent;
$templates = array();
if ( $parent_id == 0 ) {
// Use default values from get_category_template()
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
$templates[] = 'category.php';
} else {
// Create replacement $templates array
$parent = get_category( $parent_id );
// Current first
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
// Parent second
$templates[] = "category-{$parent->slug}.php";
$templates[] = "category-{$parent->term_id}.php";
$templates[] = 'category.php';
}
return locate_template( $templates );
}
add_filter( 'category_template', 'new_subcategory_hierarchy' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment