How to Limit Archives to Parent CPT Only
If you’re working with hierarchical custom post types, you may run into a scenario where you just want to feature the topmost parent item on an archive page. For example, let’s say you have a hierarchical custom post type called Books and under each book, you’re making child items of chapters. Maybe you’re categorizing the books into genres like Mystery, Romance, Biographical, etc.
In this scenario, if you went to the Mystery genre page, you would just want the main books to come up, not individual chapters of mystery books. A function like the following would limit the returned posts to just the top-level posts.
/** * Limit genre taxonomies to parent book CPTs */ function klf_books_genre_tax( $query ) { // replace 'genre' with the name of your taxonomy, if needed if ( $query->is_tax('genre') ) { // replace 'books' with the name of your CPT, if needed $query->set( 'post_type', array('books') ); // this line tells it to ONLY return parent items $query->set( 'post_parent', 0 ); } } add_action( 'pre_get_posts', 'klf_books_genre_tax' );