2017-08-24 103 views
1

我一直試圖在有幾個條件的Wordpress中設置一個基本側欄。顯示該父頁面的一級父項和子項

  1. 如果它是一個頂級頁面,顯示兒童
  2. 的第一級。如果它是一個子頁面,顯示父和它的兄弟姐妹

我得到的一些結果與此,但它增加了不是直接孩子的頁面。

<?php 
if($post->post_parent) 
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); 
else 
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0"); 
if ($children) { ?> 
    <?php echo '<h4>Explore ' . get_the_title($parent[1]) . '</h4>'; ?> 
<?php echo $children; ?> 

回答

0

有2個部分對這個問題

  1. 限制孩子剛1級:您可以通過depthwp_list_pages(),到可以指定層次的水平。
  2. 如果它是子頁面,請在列表中包含父項 - 但僅包含父項而不包含其兄弟。
    要將父項添加到列表中,您需要做的事情有點不同 - 您必須首先編譯想要獲取的所有頁面的ID列表,然後將其傳遞到wp_list_pages。

下面的代碼是未經測試,但邏輯應該是正確的:

if($post->post_parent){ 
    // get a list of all the children of the parent page 
    $pages = get_pages(array('child_of'=>$post->post_parent)); 

    if ($pages) { 
     // get the ids for the pages in a comma-delimited string 
     foreach ($pages as $page) 
      $page_ids[] = $page->ID; 
     $siblings = implode(',',$page_ids); 

     // $pages_to_get is a string with all the ids we want to get, i.e. parent & siblings 
     $pages_to_get = $post->post_parent.','.$siblings; 

     // use "include" to get only the pages in our $pages_to_get 
     $children = wp_list_pages("include=".$pages_to_get."&echo=0"); 
    } 

} 
else{ 
    // get pages that direct children of this page: depth=1 
    $children = wp_list_pages("title_li=&child_of=".$post->ID."&depth=1&echo=0"); 
} 

// display the children: 
if ($children) { 
    echo '<h4>Explore ' . get_the_title($parent[1]) . '</h4>'; 
    echo $children; 
} 
?> 
+0

感謝您的答覆!不幸的是似乎沒有出現。我沒有看到任何語法問題,並嘗試調整它,但沒有任何運氣。它目前在頂層頁面和子頁面上沒有顯示任何內容。 –

+0

如果您在每個階段爲變量添加'var_dump's,您是否在任何時候獲得任何結果? – FluffyKitten

+0

@TrevorCollinson我剛剛測試過它,它對我的​​工作很完美。你有沒有注意到我沒有在你的代碼中包含顯示'$ children'的其他代碼?我只改變了'if-else',所以我只包含這些行。我已經更新了我的答案以添加它們,以防萬一您忘記保留它們:-) – FluffyKitten

相關問題