首页 > 解决方案 > 如何在wordpress中只获取至少有一个孩子的父页面?

问题描述

我想显示作为父页面的页面列表,以及分配给它的至少一个孩子的页面列表。我正在使用以下查询,但不幸的是它没有给出预期的输出。我有什么遗漏吗,任何帮助都应该对我有用。

$args = array(
        'post_type'     => 'page',
        'post_parent' => 0
    );

    // query
    $the_query = new WP_Query( $args );

    // loop through posts
    if( $the_query->have_posts() ): ?>
        <?php while( $the_query->have_posts() ) : $the_query->the_post();?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php endwhile; ?>
    <?php endif;

标签: wordpresspost

解决方案


这对我来说是工作。试试这个代码

add_action( 'init', 'parent_pages' );
function parent_pages(){
    $args = array(
        'post_type'  => 'page',        
        'numberposts' => -1        
    );
    $the_query = get_posts( $args );
   foreach ($the_query as $key) {  
        if(!empty(get_children( $key->ID ))){               
            echo '<a href="'.$key->guid.'">'.$key->post_title.'</a>';              
        }
    }       
}


推荐阅读