Created
December 10, 2021 20:01
-
-
Save pixeldevsio/5756ac8f3ff29791a5acd8e29a98d9ce to your computer and use it in GitHub Desktop.
Create custom WordPress structure for parent 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 | |
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); | |
// $parent->post_name is the slug of the parent. This is your folder structure inside your theme | |
$child_template = locate_template( | |
[ | |
'page-templates/' . $parent->post_name . '/page-' . $post->post_name . '.php', | |
'page-templates/' . $parent->post_name . '/page-' . $post->ID . '.php', | |
'page-templates/' . $parent->post_name . '/child.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