【问题标题】:Displaying first level parent and co-children of that parent page显示该父页面的第一级父级和共同子级
【发布时间】:2017-08-24 20:01:36
【问题描述】:

我一直在尝试在 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; ?>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    这个问题分为两部分

    1. 将子级限制为仅 1 级:您可以将 depth 传递给 wp_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; 
    } 
    ?>
    

    【讨论】:

    • 感谢您的回复!不幸的是,似乎什么都没有出现。我没有看到任何语法问题,并尝试对其进行一些调整,但没有任何运气。它目前在顶级页面和子页面上没有显示任何内容。
    • 如果你为每个阶段的变量添加var_dumps,你在任何时候都得到任何结果吗?
    • @TrevorCollinson 我刚刚对其进行了测试,它对我来说非常适合。您可能没有注意到我没有在我的答案中包含显示$children 的其余代码吗?我只更改了if - else,所以我只包含了这些行。我已经更新了我的答案以添加它们,以防你忘记保留它们:-)
    • 啊,是的,我完全没有把它们结合起来。它运行良好。非常感谢!
    • 就是这样!我正在寻找已解决的按钮。多年转向 Stackoverflow,这是我的第一个问题。感谢您帮助使这个网站成为现在的样子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2013-02-26
    • 2020-01-21
    • 2016-08-22
    • 2020-12-09
    相关资源
    最近更新 更多