Last active
August 29, 2015 14:06
-
-
Save code26/4191435f909415391b4a to your computer and use it in GitHub Desktop.
Automatic template selector for Wordpress Ancestor/Child Pages
This file contains 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
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