Skip to content

Instantly share code, notes, and snippets.

@code26
Last active August 29, 2015 14:06
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 code26/4191435f909415391b4a to your computer and use it in GitHub Desktop.
Save code26/4191435f909415391b4a to your computer and use it in GitHub Desktop.
Automatic template selector for Wordpress Ancestor/Child Pages
function jsp_switch_page_template() {
global $post;
if (is_page() && !get_page_template_slug( $post->ID )) { //if no template was selected via WP
$ancestors = $post->ancestors;
if ($ancestors) {
$templatePath = TEMPLATEPATH . '/';
$prefix = 'page-'; //default page template prefix
$ext = '.php';
$appender = '_child';
$parent_id = get_post( end($ancestors) );
$parent_slug = $parent_id->post_name;
$page_template = $prefix.$post->post_name.$ext; //default template
$parent_page_template = $prefix.$parent_slug.$ext; //ancestor template
$parent_page_child_template = $prefix.$parent_slug.$appender.$ext; //children template
$template = file_exists($templatePath.$page_template) ? $templatePath.$page_template : file_exists($templatePath.$parent_page_child_template) ? $templatePath.$parent_page_child_template : $templatePath.$parent_page_template;
if (file_exists($template)) {
load_template($template);
exit;
}
} else {
return true;
}
}
}
add_action('template_redirect','jsp_switch_page_template');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment