To exclude posts that have a parent (i.e., child posts) in a WP_Query
request, you can use the post_parent
argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0
, which means that only top-level posts (posts without a parent) will be included in the query.
Here’s an example query:
$args = array(
'post_type' => 'post', // Replace with the desired post type
'post_parent' => 0, // Exclude child posts
'posts_per_page' => -1 // Number of posts to retrieve (adjust as needed)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Your code to display posts
}
} else {
// No posts found
}
wp_reset_postdata();
The key part here is the post_parent => 0
argument, which excludes all posts that have a parent.