How to exclude post type from search but retain taxonomy archive listing

If you have set a post type to be excluded from search, you may have noticed that this has an odd drawback of also excluding the post type from any term archives for custom taxonomies as well.

This is a detail coming from how WordPress core handles the query for the term archive. If you’re needing to retain the exclusion from search functionality, while still retaining archive inclusion, it is better to make use of the code below.

First you’ll want to re-set “Exclude from Search” back to false in your post type settings. Next you’ll want to modify and add the code below to your active theme’s functions.php file.

function my_cptui_custom_exclude_post_type_search( $query ) {
	// We do not want unintended consequences.
	if ( is_admin() || ! $query->is_main_query() ) {
		return;
	}

	if ( is_search() ) {
		// Get an array of all searchable post types.
		$searchable_types = get_post_types( array( 'exclude_from_search' => false ) );
		// Unset the one we don't want to be searchable
		unset( $searchable_types['movie'] );

		$query->set(
			'post_type',
			$searchable_types
		);
	}
}
add_filter( 'pre_get_posts', 'my_cptui_custom_exclude_post_type_search' );

Here we are hooking into the pre_get_posts filter, and grabbing all of the searchable post type slugs, and then unsetting movie as our example post type. This solves our issue of not being able to search “movie” post types, but still allow them as part of term archives associated with movie .

Updated Dec 9, 2022 8:40 PM