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; } );