Get parents child pages

时间:2016-10-05 作者:Maarten Wolfsen

我有以下代码:

<?php

    global $post;

    $children = get_pages( array( \'child_of\' => $post->ID ) );

    if ( is_page() && $post->post_parent > 0 )
    { 
        // Is subpage
        // Here I want to get all sibling from the current page
    } 
    else 
    {
        // Is no subpage
        if( count( $children ) == 0 ) 
        {
            // Has no children
        } 
        else 
        {
            // Has children
            echo \'<div class="subnav-header">\';
            echo \'<div class="subnav-table">\';
            echo \'<ul>\';
            foreach($children as $child){ ?>
                <li><a href="<?php echo $child->guid; ?>"><?php echo $child->post_title; ?></a></li>
            <?php }
            echo \'</ul>\';
            echo \'</div>\';
            echo \'</div>\';
        }

    }

?>
首先,它检测当前页面是子页面还是普通页面。当页面是子页面时,我希望显示当前页面的所有同级页面,就像我在页面没有子页面且有子页面时所做的那样。

简而言之,我想做的是:

当当前页面是子页面时,请检查该页面是否有同级页面

1 个回复
最合适的回答,由SO网友:Maarten Wolfsen 整理而成

解决了这个问题,我决定最好在这里发布我的答案,因为人们可以从中学习:)

<?php


    global $post;

    $children = get_pages( array( \'child_of\' => $post->ID ) );
    $siblings = get_pages( array( \'child_of\' => $post->post_parent ) );

    // or, if you want to exclude the current page:
    // $siblings = get_pages( array( \'child_of\' => $post->post_parent, \'exclude\' => $post->ID ) );

    if ( is_page() && $post->post_parent > 0 )
    { 
        // Is subpage
        if( count( $siblings ) == 0 )
        {
            // Has no siblings
        }
        else
        {
            // Has siblings
            echo \'<div class="subnav-header">\';
            echo \'<div class="subnav-table">\';
            echo \'<ul>\';
            foreach($siblings as $sibling){ ?>
                <li><a href="<?php echo $sibling->guid; ?>"><?php echo $sibling->post_title; ?></a></li>
            <?php }
            echo \'</ul>\';
            echo \'</div>\';
            echo \'</div>\';
        }
    } 
    else 
    {
        // Is no subpage
        if( count( $children ) == 0 ) 
        {
            // Has no children
        } 
        else 
        {
            // Has children
            echo \'<div class="subnav-header">\';
            echo \'<div class="subnav-table">\';
            echo \'<ul>\';
            foreach($children as $child){ ?>
                <li><a href="<?php echo $child->guid; ?>"><?php echo $child->post_title; ?></a></li>
            <?php }
            echo \'</ul>\';
            echo \'</div>\';
            echo \'</div>\';
        }

    }

?>