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 transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more