Remove custom post types from search result

// Remove custom post types from search result
add_action('pre_get_posts', 'remove_cpts_from_search_results');
function remove_cpts_from_search_results($query) {
	if (is_admin() || !$query->is_main_query() || !$query->is_search()) {
		return $query;
	}
	$post_types_to_exclude = array('custom-post-type-1', 'custom-post-type-2');
	if ($query->get('post_type')) {
		$query_post_types = $query->get('post_type');
		if (is_string($query_post_types)) {
			$query_post_types = explode(',', $query_post_types);
		}
	} else {
		$query_post_types = get_post_types(array('exclude_from_search' => false));
	}
	if (sizeof(array_intersect($query_post_types, $post_types_to_exclude))) {
		$query->set('post_type', array_diff($query_post_types, $post_types_to_exclude));
	}
	return $query;
}
My website may contain fan art inspired by existing characters from movies or tv shows, I dont own any rights. Any copyright owner willing to remove those fan arts can contact me here. This is a personal portfolio, the sole use of cookies are for analysing my traffic through Google Analytics, if you're ok with that please accept this terms by closing this disclaimer.