How to exclude posts with parent post in wp_query, WordPress

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.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to check if an array has at least one non-empty value in php, WordPress?

To check if there is at least one non-empty value in an array in PHP, including scenarios using WordPress, you can use the following methods: Method 1: Using array_filter The array_filter function removes all empty values from an array and returns a new array. If the filtered array is not empty, it means that there…
Read more