我对上述Ozzychech解决方案的修改。此函数在主题的根目录中查找名称包含父级slug或父级ID的文件。
/theme_root/child-PARENT_SLUG.php
/theme_root/child-PARENT_ID.php
function child_templates($template) {
global $post;
if ($post->post_parent) {
// get top level parent page
$parent = get_post(
reset(array_reverse(get_post_ancestors($post->ID)))
);
// find the child template based on parent\'s slug or ID
$child_template = locate_template(
[
\'child-\' . $parent->post_name . \'.php\',
\'child-\' . $parent->ID . \'.php\',
\'child.php\',
]
);
if ($child_template) return $child_template;
}
return $template;
}
add_filter( \'page_template\', \'child_templates\' );