Skip to content

Instantly share code, notes, and snippets.

@lori
Created January 31, 2013 22:06
Show Gist options
  • Save lori/4687002 to your computer and use it in GitHub Desktop.
Save lori/4687002 to your computer and use it in GitHub Desktop.
Make subcategories inherit parent category templates
<?php
/*
* Make subcategories inherit parent category templates
*/
function hierarchical_page_template_redirect () {
$cat = get_queried_object();
if ( is_category() && $cat->category_parent == 100 ) { // Parent category ID
if ( file_exists( locate_template( array('category-cat_name.php'), true ) ) ) { // Category template
}
elseif ( ! $cat->category_parent ) {
return;
} else {
$ancestors = get_category_ancestors($cat);
foreach ($ancestors as $ancestor_cat_id) {
if ( file_exists ( locate_template( array('category-cat_name.php'), true ) ) ) {
exit;
}
}
foreach ($ancestors as $ancestor_cat_id) {
$ancestor_slug = get_post($ancestor_cat_id)->post_name;
if ( file_exists ( locate_template( array('category-cat_name.php'), true ) ) ) {
exit;
}
}
$current_page_template = get_post_meta($post->ID,'_wp_page_template',true);
if ( file_exists ( locate_template ( array('/' . $current_page_template ), true ) ) ) {
exit;
} else {
foreach ($ancestors as $ancestor_cat_id) {
$ancestor_page_template = get_post_meta($ancestor_cat_id,'_wp_page_template',true);
if ( file_exists ( locate_template ( array('/' . $ancestor_page_template ), true ) ) ) {
exit;
}
}
}
}
exit;
}
}
add_action('template_redirect','hierarchical_page_template_redirect');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment