是否可以检查页面是父页面还是子页面?
我的页面设置如下:
- 家长
----儿童第1页
----儿童第2页
等等
我想显示某个菜单,如果它是父页面,如果它在子页面上则显示不同的菜单.
我知道我可以做类似下面的事情,但我想让它更有活力而不包括特定的页面ID.
<?php
if ($post->post_parent == '100') { // if current page is child of page with page ID 100
// show image X
}
?>
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 59
您可以测试后是这样子页面:
*(从http://codex.wordpress.org/Conditional_Tags)*
<?php
global $post; // if outside the loop
if ( is_page() && $post->post_parent ) {
// This is a subpage
} else {
// This is not a subpage
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 7
我知道这是一个老问题,但我一直在寻找同样的问题,直到我想出这个问题才找到一个清晰而简单的答案。我的回答没有回答他的解释,但它回答了我一直在寻找的主要问题。
这会检查页面是子页面还是父页面,并允许您仅在子页面或父页面上显示,例如侧边栏菜单,而不是在没有父页面或子页面的页面上显示。
<?php
global $post;
$children = get_pages( array( 'child_of' => $post->ID ) );
if ( is_page() && ($post->post_parent || count( $children ) > 0 )) :
?>
Run Code Online (Sandbox Code Playgroud)
小智 7
对于 WordPress,您可以简单地检查:
<?php
if (wp_get_post_parent_id(get_the_ID())) {
echo "I am a child page";
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 5
把这个函数放在你的主题的functions.php 文件中。
function is_page_child($pid) {// $pid = The ID of the page we're looking for pages underneath
global $post; // load details about this page
$anc = get_post_ancestors( $post->ID );
foreach($anc as $ancestor) {
if(is_page() && $ancestor == $pid) {
return true;
}
}
if(is_page()&&(is_page($pid)))
return true; // we're at the page or at a sub page
else
return false; // we're elsewhere
};
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它:
<?php
if(is_page_child(100)) {
// show image X
}
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53629 次 |
| 最近记录: |