-
-
Save dgoze/76c7c952cbbf1f5db80bf35090f40db3 to your computer and use it in GitHub Desktop.
Switch template based on page parent or grandparent. Requires the page parent template is set.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Switch template based on page parent or grandparent. Requires the page parent template is set. | |
add_action('template_include', 'auto_child_template'); | |
function auto_child_template( $template = '' ) { | |
global $post; | |
if ( ! is_page() ) { | |
return $template; | |
} | |
else { | |
$page = get_queried_object(); | |
$ancestors = get_post_ancestors( $post ); | |
$templates = array(); | |
// add ancestors page templates to $templates array | |
foreach ( $ancestors as $ancestor ) { | |
$templates[] = get_page_template_slug( $ancestor ); | |
} | |
// remove empty values | |
$templates = array_filter($templates); | |
// if no ancestors has a template return current one | |
if ( empty($templates) ) return $template; | |
// fallback | |
$templates[] = 'page.php'; | |
return locate_template( $templates, FALSE ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment