How to query for posts (in hierarchical custom post type) that have children?

I’m trying to figure out how to query for posts in my hierarchical custom post type, presumably using WP_Query that have child posts. I can get all pages that don’t have children by setting 'post_parent' => 0 in my WP_Query args, but that returns all posts that are not children. I need only posts that have child posts.

Related posts

2 comments

  1. You can use the post_parent__not_in parameter:

    $args = array( 
               'post_type'           => 'cpt',
               'post_parent__not_in' => array( 0 ) 
    );
    $query = new WP_Query( $args );
    

    to retrieve child posts of type cpt.

    The generated SQL will then include this part:

    wp_posts.post_parent NOT IN (0)
    
  2. As far I have understood your requirement, I guess this is what you need.

    I have documented the code, please go thru it.

    <?php
    /*
    Idea:   Collecting all the posts child posts by --->'post_parent__not_in' => array( 0 )<--- 
            in wp_query. Then find their parent posts by eliminating duplicates.
    */
    
        $query_array = array(
                //Change this post type to your Custom-Post-Type.
            'post_type' => 'news',
                //Showing all posts
            'posts_per_page' => -1, 
                //Giving all child posts only
            'post_parent__not_in' => array( 0 ) 
            );
    
        $the_query = new WP_Query($query_array);
            //Array to collect all parent posts
        $collect_parents = array();
        while($the_query->have_posts()):
            $the_query->the_post();
                //if condition is used to eliminate duplicates, generated by same child post of parent.
            if(!in_array($post->post_parent, $collect_parents)){
                //$collect_parents contains all the parent post id's
                $collect_parents[] = $post->post_parent;
            }
    
        endwhile;
            //Printing all the parent posts
        foreach($collect_parents as $parent){
            ?>
            <!-- Printing parent post title -->
            <h2><a href="<?php echo get_permalink($parent ); ?>"> <?php echo get_the_title($parent); ?></a></h2>
            <!-- Printing parent post content -->
            <p><?php echo get_post_field( 'post_content', $parent); ?></p>
            <?php
        }
    ?>
    

Comments are closed.