Abhee
Abhee

Reputation: 425

How to get only parent pages who has atleast one child in wordpress?

I want to display list of pages who are parent pages, and who has atleast one child assigned to it. I am using below query, but unfortunately it doesn't give expected output. Is there something i am missing, any help should be useful to me.

$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;

Upvotes: 0

Views: 322

Answers (1)

Nidhi Patel
Nidhi Patel

Reputation: 396

This is work for me. Try this code

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>';              
        }
    }       
}

Upvotes: 1

Related Questions