我正在尝试在 WordPress 中创建兄弟页面(不是帖子)列表来填充页面的侧边栏。我编写的代码成功返回了页面的父级标题。
<?php
$parent_title = get_the_title($post->post_parent);
echo $parent_title; ?>
据我了解,您需要页面的 id(而不是标题)来检索页面的兄弟姐妹(通过wp_list_pages)。如何获取页面的父 ID?
欢迎使用其他方法。目标是列出页面的兄弟姐妹,不一定只是检索父级的 id。
我正在尝试在 WordPress 中创建兄弟页面(不是帖子)列表来填充页面的侧边栏。我编写的代码成功返回了页面的父级标题。
<?php
$parent_title = get_the_title($post->post_parent);
echo $parent_title; ?>
据我了解,您需要页面的 id(而不是标题)来检索页面的兄弟姐妹(通过wp_list_pages)。如何获取页面的父 ID?
欢迎使用其他方法。目标是列出页面的兄弟姐妹,不一定只是检索父级的 id。
$post->post_parent
正在给您父 ID,$post->ID
将给您当前页面 ID。因此,以下将列出页面的兄弟姐妹:
wp_list_pages(array(
'child_of' => $post->post_parent,
'exclude' => $post->ID
))
wp_list_pages(array(
'child_of' => $post->post_parent,
'exclude' => $post->ID,
'depth' => 1
));
正确答案,因为其他两个答案都不会专门显示兄弟姐妹。
此页面上的一些答案的信息有些过时。即,exclude
使用时似乎不再需要child_of
.
这是我的解决方案:
// if this is a child page of another page,
// get the parent so we can show only the siblings
if ($post->post_parent) $parent = $post->post_parent;
// otherwise use the current post ID, which will show child pages instead
else $parent = $post->ID;
// wp_list_pages only outputs <li> elements, don't for get to add a <ul>
echo '<ul class="page-button-nav">';
wp_list_pages(array(
'child_of'=>$parent,
'sort_column'=>'menu_order', // sort by menu order to enable custom sorting
'title_li'=> '', // get rid of the annoying top level "Pages" title element
));
echo '</ul>';
<?php if($post->post_parent): ?>
<?php $children = wp_list_pages('title_li=&child_of='.$post->post_parent.'&echo=0'); ?>
<?php else: ?>
<?php $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0'); ?>
<?php endif; ?>
<?php if ($children) { ?>
<ul class="subpage-list">
<?php echo $children; ?>
</ul>
<?php } ?>
不要使用 exclude 参数,只需针对 .current_page_item 进行区分。