2010-02-23 88 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>';