您的代码示例存在一些问题:
1) $post->post_parent 没有被检查任何其他东西,所以它只会在它是一个子页面时返回true(不一定是你想要定位的页面的子页面)
2) get_sidebar()被错误地调用。如果你想从你的主题文件夹中获取 'sidebar-test-may12.php',你需要调用 get_sidebar('test-may12')
3)您的函数调用后缺少分号
所以你的代码应该是这样的:
<?php
if(is_page(1997) || $post->post_parent == 1997) {
get_sidebar('test-may12'); //get sidebar-test-may12.php
}
else{
get_sidebar(); //get sidebar.php
}
?>
让我知道这是否有帮助。
更新:请记住, $post->post_parent 不会获得子页面的最顶层祖先 ID。如果您想获取顶级 ID 而不管深度如何,请考虑执行以下操作:
<?php
$ancestors = get_ancestors(get_the_ID(), 'page');
if(is_page(1997) || end($ancestors) == 1997)
get_sidebar('test-may12'); //get sidebar-test-may12.php
else
get_sidebar(); //get sidebar.php
?>
可能的解决方案:基于您的示例和我提出的祖先检查,您可以做的一件事是让您的模板检查基于父页面的 slug 在您的主题中是否存在特殊的侧边栏。这样,如果您决定一个特定的页面需要一个特殊的侧边栏,它及其所有的子/孙/曾孙/等。您只需将其添加到您的主题中,名称为“sidebar-{parent_slug}.php”。所以:
<?php
$id = get_the_ID();
$ancestors = get_ancestors($id, 'page');
$top_page = $ancestors ? get_page(end($ancestors)) : get_page($id);
if(locate_template('sidebar-'.$top_page->post_name.'.php'))
get_sidebar($top_page->post_name);
else
get_sidebar();
?>
这样,您不需要大量的条件来决定在通用页面模板上加载哪个侧边栏文件。