admin管理员组

文章数量:1302939

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?

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?

Share Improve this question asked Mar 10, 2021 at 20:03 scpers0nscpers0n 536 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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.

本文标签: Query to Exclude Child Pages from Custom Post Type Archive