dsyrdwdbo47282676 2018-07-03 08:40
浏览 94
已采纳

在子页面列表上显示父页面

I have a script that is displaying child page list on parent page and a list o child pages without the current child page.

I would like to add the parent page on child pages, but I don't know how to achieve it. Could you please help me out?

This is my code:

if ('page-parent') {
echo '<h3>See also</h3>';
  // if we are on a parent page set the $parent variable to current post id
  // otherwise set $parent variable to current post parent
  $parent = $post->post_parent == 0 ? $post->ID : $post->post_parent;

  // if we use current post parent as $parent, exclude the current page
  $exclude = $parent == $post->post_parent ? $post->ID : false;

  // get all the children
  $args = array( 'parent' => $parent, 'sort_column' => 'menu_order' );
  if ( $exclude ) $args['exclude'] = $exclude;
  $child_pages = get_pages($args);

  // show only if there are children
  if ( ! empty($child_pages) ) {
    global $post;
    foreach ( $child_pages as $post ) { setup_postdata( $post );
    ?>
    <div class="child-thumb">
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </div>
    <?php
    }
    wp_reset_postdata();
  }

}

  • 写回答

1条回答 默认 最新

  • dps43633 2018-07-03 09:11
    关注

    You need to use 'child_of' argument instead of 'parent'. 'parent' in get_pages means to fetch or not to fetch parental pages. But your case needs to fetch children of given page.

    So you must use

    $args = array( 'child_of' => $parent, 
    'sort_column' => 'menu_order' );
    

    To display one single parent page above children, you can use get_post function:

    if ($post->post_parent>0){
    $parent_page=get_post($post->post_parent);
    echo '<div>'.$parent_page->post_title.'</div>';
    }
    if ( ! empty($child_pages) ) {
    ///and so on...
    

    For more information: https://codex.wordpress.org/Function_Reference/get_pages

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料