2010-02-23 90 views
9

我想在WordPress中创建一个兄弟页面列表(不是帖子)来填充页面的侧边栏。我成功编写的代码返回页面的父级标题。如何检索Wordpress页面的兄弟页面的列表?

<?php 
$parent_title = get_the_title($post->post_parent); 
echo $parent_title; ?> 

据我了解,你需要一个页面的ID(而不是名称)来检索网页的兄弟姐妹(通过wp_list_pages)。我怎样才能得到页面的父母的ID?

欢迎使用其他方法。目标是列出一个页面的兄弟姐妹,不一定只是检索父母的ID。

回答

23

$post->post_parent给你的家长ID,$post->ID会给你当前的页面ID。因此,下面将列出一个页面的兄弟姐妹:

wp_list_pages(array(
    'child_of' => $post->post_parent, 
    'exclude' => $post->ID 
)) 
4
<?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 } ?> 

不要使用.current_page_item区分排除参数,只是目标。

+0

对于这个问题最好的解决办法IMO – benpalmer 2012-01-05 11:06:06

14
wp_list_pages(array(
    'child_of' => $post->post_parent, 
    'exclude' => $post->ID, 
    'depth' => 1 
)); 

正确的答案,因为其他答案都不排除显示兄弟姐妹。

2

此页面上的部分答案略有过时的信息。即使用child_of时,似乎不再需要exclude

这里是我的解决方案:

// 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>';