dr9379 2017-02-23 09:46
浏览 86

获取当前页面的子页面以及当前页面链接

I intend to create a sidebar to retrieve a list of the current page's children as well as the current page itself. Here is the code that I have been using which retrieves the current pages children even when on the child pages, however when I try to include the $parent as $post->post_parent it displays all pages

    <?php
   if ($post->post_parent)  {
        $ancestors=get_post_ancestors($post->ID);
        $root=count($ancestors)-1;
        $parent = $ancestors[$root];
    } else {
        $parent = $post->ID;
    }
    $children = wp_list_pages("title_li=&child_of=". $parent ."&echo=0");
    $parent = wp_list_pages("title_li=&child_of=". $post->post_parent ."&echo=0");
    if ($children) { ?>
    <ul class="tabs">
        <?php echo  $parent ?>
        <?php echo $children; ?>
    </ul>
<?php } ?>
  • 写回答

2条回答 默认 最新

  • dsh77114 2017-02-23 11:09
    关注
    /*-------------------------------------------------------------------
        Return parent page ID or child as else. Add this to functions.php
    ---------------------------------------------------------------------*/
    
    function get_top_parent_page_id() { 
        global $post; 
    
        if ($post->ancestors) { 
            return end($post->ancestors); 
        } else { 
            return $post->ID; 
        } 
    }
    

    //Use this in the template

    <?php while ( have_posts() ) : the_post(); 
    
        //Add parent page slug into arguments
        $query = new WP_Query('pagename=page_slug');
        if ($query->have_posts() ){ while ($query->have_posts() ) { $query->the_post(); } }
    
        //Get children by calling function in functions.php for the top parent id                  
        $current_page_id = get_top_parent_page_id();
        $args = array( 'post_type' => 'safaris', 'post_parent' => $current_page_id, 'orderby' => 'title', 'order' => 'ASC' );
        $child_query = new WP_Query($args);
    
        $i = 0; 
        if ($child_query->have_posts() ){ while ($child_query->have_posts() ){ $child_query->the_post(); 
        $i++; if( 1 == $i ) { ?>
    
        <li role="presentation" class="active"><?php the_title(); ?></li>
    
        <?php } else { ?>
    
        <li role="presentation"><?php the_title(); ?></li>
    
        <?php } } } wp_reset_postdata();  endwhile; ?>  
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题