2017-08-24 100 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

相关问题