Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active May 21, 2016 02:20
Show Gist options
  • Save kjbrum/0b0356a5b6ce2f1fee34 to your computer and use it in GitHub Desktop.
Save kjbrum/0b0356a5b6ce2f1fee34 to your computer and use it in GitHub Desktop.
Force sub pages to have the same template as parent
<?php
/**
* Force child pages to have the same template as their parent
*
* @param boolean $include_grandchildren Whether to include grandchildren
* @return void
*/
function wp_force_parent_template( $include_grandchildren=false ) {
global $post;
if( is_page() ) {
if( $include_grandchildren ) {
// Apply to children and grandchildren
$ancestors = $post->ancestors;
if( $ancestors ) {
$parent_page_template = get_post_meta( end( $ancestors ), '_wp_page_template', true );
$template = TEMPLATEPATH . "/{$parent_page_template}";
if( file_exists( $template ) ) {
load_template( $template );
exit;
}
} else {
return true;
}
} else {
// Apply to just children
if( $post->post_parent == 0 )
return true;
else if( $post->post_parent != $post->ID ) {
$parent_page_template = get_post_meta( $post->post_parent, '_wp_page_template', true );
$template = TEMPLATEPATH . "/{$parent_page_template}";
if( file_exists( $template ) ) {
load_template( $template );
exit;
}
}
}
}
}
add_action( 'template_redirect', 'wp_force_parent_template' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment