Created
August 21, 2020 16:22
-
-
Save kodie/b69403a9a0cf09dd8a77765f32ecf06a to your computer and use it in GitHub Desktop.
Allows for subpages to have their own unique templates in WordPress (ie. /my-page/edit/ uses page-my-page-edit.php)
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
<?php | |
// Allows for subpages to have their own unique templates (ie. /my-page/edit/ uses page-my-page-edit.php) | |
add_filter('template_include', 'get_subpage_template'); | |
function get_subpage_template($template, $page_id = null) { | |
if ($page_id === null) { | |
global $wp_query; | |
$page = $wp_query->queried_object; | |
} else { | |
$page = get_post($page_id); | |
} | |
if ($page && $page->post_type === 'page') { | |
$ancestors = get_post_ancestors($page->ID); | |
if (!empty($ancestors)) { | |
$new_template = get_template_directory() . '/page'; | |
foreach($ancestors as $ancestor) { | |
$new_template .= '-' . get_post_field('post_name', $ancestor); | |
} | |
$new_template .= '-' . $page->post_name . '.php'; | |
if (file_exists($new_template)) { | |
return $new_template; | |
} | |
return get_subpage_template($template, end($ancestors)); | |
} | |
} | |
return $template; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment