Query to Exclude Child Pages from Custom Post Type Archive

I have a hierarchical custom post type called Services. On the Services archive page I want to display only parent Services and exclude child Services.

I found similar answers to my question, which is to customize the main query within archive-services.php using the following:

function exclude_children( $query ) {
    if ( $query-is_main_query()  !is_admin()  $query-is_post_type_archive( 'services' ) ) {
        $query-set( 'post_parent', 0 );
    }
}
add_action( 'pre_get_posts', 'exclude_children' );

But the child services are still displayed. Why doesn't this work?

Topic children pre-get-posts wp-query custom-post-types Wordpress

Category Web


I realized the reason it doesn't work: this function needs to be located in functions.php.

Per WP code reference: pre_get_posts "Fires after the query variable object is created, but before the actual query is run." Since I placed the function within an archive template, the main query had already fired, and was thus too late.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.