Only Top-Level Items on Hierarchical Post Type Archives
Lists only parent items on the archive of hierarchical post types, such as services with sub-services, so child items do not crowd the overview.
Opens WPIDE on
Code
// Hierarchical post types whose archive lists only top-level items (child items stay reachable through their parents).
// Empty = every public hierarchical custom post type with an archive.
$wpide_top_level_archive_types = array();
add_action( 'pre_get_posts', function ( $query ) use ( $wpide_top_level_archive_types ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_post_type_archive() ) {
return;
}
$type = $query->get( 'post_type' );
$type = is_array( $type ) ? reset( $type ) : $type;
$obj = $type ? get_post_type_object( $type ) : null;
if ( ! $obj || ! $obj->hierarchical || ( $wpide_top_level_archive_types && ! in_array( $type, $wpide_top_level_archive_types, true ) ) ) {
return;
}
$query->set( 'post_parent', 0 );
} );
Notes
Leave the list empty to apply to every hierarchical post type archive, or name the exact types.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.