如何在wordpress中获取父页面的所有子页面?

kra*_*hos 10 php wordpress parent-child

例:

About
--- Menu 1
--- Menu 2
--- Menu 3
--- Menu 4
Run Code Online (Sandbox Code Playgroud)

如果我在页面...我有子页面.但是,如果进入菜单1,所有页​​面都会消失

我需要的是一直看到父页面

目前我有这个代码

<? if (is_page()) {
    $g_page_id = $wp_query->get_queried_object_id();
    wp_list_pages("depth=4&title_li=&child_of=".$g_page_id."&sort_column=menu_order");
   }
?>
Run Code Online (Sandbox Code Playgroud)

谢谢!

解决

我用这个并且工作正常!

<?php
if ( is_page() ) :
    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' );
    endif;
    if ($children) : ?>
        <div class="title">
            <?php
            $parent_title = get_the_title( $post->post_parent );
            echo $parent_title;
            ?>
            <span></span>
        </div>
        <ul>
            <?php echo $children; ?>
        </ul>
    <?php
    endif;
endif;
?>
Run Code Online (Sandbox Code Playgroud)

Jos*_*bre 8

干得好.对作者来说有点晚了,但人们会来这里寻求答案;-)

<?php 
// determine parent of current page
if ($post->post_parent) {
    $ancestors = get_post_ancestors($post->ID);
    $parent = $ancestors[count($ancestors) - 1];
} else {
    $parent = $post->ID;
}

$children = wp_list_pages("title_li=&child_of=" . $parent . "&echo=0");

if ($children) {
?>

    <ul class="subnav">
        <?php 
            // current child will have class 'current_page_item'
            echo $children; 
        ?>
    </ul>

<?php 
} 
?>
Run Code Online (Sandbox Code Playgroud)

  • 您已经在`$ post-> post_parent`中拥有父ID,那么为什么要使用`get_post_ancestors`来获取父项? (2认同)

D. *_*ell 7

处理此问题的最简单方法是使用get_children(). 它几乎可以满足您的期望。它返回父页面的子页面。

get_children()基本上是WP_Query类的包装器。

你可以这样使用它......

$child_args = array(
    'post_parent' => 1, // The parent id.
    'post_type'   => 'page',
    'post_status' => 'publish'
);

$children = get_children( $child_args );
Run Code Online (Sandbox Code Playgroud)

如果你想返回当前帖子的孩子,你可以$post->ID作为'post_parent'.

文档 get_children()

文档 WP_Query