Skip to content

Instantly share code, notes, and snippets.

@diegochavez
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegochavez/d8a5280760ad734b9aec to your computer and use it in GitHub Desktop.
Save diegochavez/d8a5280760ad734b9aec to your computer and use it in GitHub Desktop.
Automatically Apply Parent Page Template To All Sub Pages In WordPress
function switch_page_template() {
global $post;
// Checks if current post type is a page, rather than a post
if (is_page())
{
// Checks if page is parent, if yes, return
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','switch_page_template');
//Now this supports sub sub pages… and sub sub sub pages and so on
function switch_page_template() {
global $post;
// Checks if current post type is a page, rather than a post
if (is_page()){
$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;
}
}
}
add_action('template_redirect','switch_page_template');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment