Aivaras
Aivaras

Reputation: 19

Wordpress displaying only children posts

im trying to display only children posts, i don't need pagination. In theory this code should query all posts and in second query get posts that have parent. But in reality it displaying all posts with parent.

<?php
            if ( get_query_var('paged') ) $paged = get_query_var('paged');  
            if ( get_query_var('page') ) $paged = get_query_var('page');

            $args1 = [
                'post_type'   => 'drama',
                'post_parent' => 0, // Only return top level pages
                'nopaging'    => true, // Alias of posts_per_page => -1, Get all top level pages  
                'fields'       => 'ids' // Only get pages ID's for performance
            ];
            $exclude_parents = get_posts( $args1 );

            // Now we can run our query as normal
            $args = [
                'post_type'    => 'drama',
                'post__not_in' => $excluse_parents, // Exclude parent pages
                'paged'        => $paged,
            ];
            $query = new WP_Query( $args );

            if ( $query->have_posts() ) : ?>
                <?php while ( $query->have_posts() ) : $query->the_post(); ?>
                    <?php $parent_p = wp_get_post_parent_id( $post_ID ); ?>             
                    <?php if ( 0 == 0 ) { ?>
                        <div class="col-md-12"><span><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></span></div>
                    <?php } ?>
                <?php endwhile; wp_reset_postdata(); ?>
                <div class="clearfix"></div>
                <?php else : ?>
                    <?php get_template_part( 'content', 'none' ); ?>
            <?php endif; ?>

Upvotes: 1

Views: 148

Answers (1)

Scarecrow
Scarecrow

Reputation: 4137

If you are looking for an algo to get those posts which have no child post then the algo should be

Step 1 : get all post id in an array(post_id_arr).

Step 2: get all post's parent id in another array(parent_id_arr);

Step 3: run a loop for parent_id_arr and remove the parent ids from post_id_arr.

Step 4: Now the post_id_arr will have only child post ids ,

Upvotes: 1

Related Questions