Last active
October 27, 2021 12:35
-
-
Save pixeldevsio/9222008d9c0b49ba3862bfe902e23e0f to your computer and use it in GitHub Desktop.
WordPress Parent and Child Page templates
This file contains hidden or 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 | |
// Use this function to add Parent and Child Page Templates | |
// Structure: | |
// theme_folder/page-templates/parent_page_slug/page.php - Parent Template | |
// theme_folder/page-templates/parent_page_slug/page-child_page_slug.php - Child Template | |
// theme_folder/page-templates/parent_page_slug/page-child_page_ID.php - Child Template | |
add_filter( | |
'page_template', | |
function ($template) { | |
global $post; | |
if ($post->post_parent) { | |
// get top level parent page | |
$parent = get_post( | |
reset(array_reverse(get_post_ancestors($post->ID))) | |
); | |
// or ... | |
// when you need closest parent post instead | |
// $parent = get_post($post->post_parent); | |
$child_template = locate_template( | |
[ | |
'page-templates/' . $parent->post_name . '/page-' . $post->post_name . '.php', | |
'page-templates/' . $parent->post_name . '/page-' . $post->ID . '.php', | |
] | |
); | |
if ($child_template) return $child_template; | |
} elseif (file_exists(get_stylesheet_directory() . '/page-templates/' . $post->post_name . '/page.php')) { | |
$parent_template = locate_template( | |
[ | |
'page-templates/' . $post->post_name . '/page.php', | |
] | |
); | |
if ($parent_template) return $parent_template; | |
} | |
return $template; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment