Wordpress | 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;
}