Edited: February 4th, 2023.
The base content type structure in WordPress are posts. Pages, Comments, Attachments, etc., are posts in WordPress.
Some plugins add their own custom post types to take advantage of the base content structure. For example, WooCommerce adds the ‘product’ custom post type. LearnDash, adds the ‘sfwd-courses’ custom post type for courses. And so on.
These custom post types, by default, are enabled to be searched. When you do a search in WordPress, the WordPress search will bring all the matching posts within the custom post types enabled to be searched.
But sometimes you may want to prevent the WordPress search from including results from certain post types.
You can remove post types from the WordPress search feature by hooking into the register_post_type_args action in WordPress.
Post types are registered with a series of arguments, that set the properties they will have. Within the arguments, you can find one called ‘exclude_from_search’.
Keep in mind, you need to know the name of the custom post type you want to exclude from the search.
Let’s say, you want to exclude WooCommerce products.
A function that exclude products would be as follows:
function obi_exclude_woocommerce_products_from_search($args, $post_type){
if( 'product' == $post_type){
$args['exclude_from_search'] = true;
}
return $args;
}
add_action('register_post_type_args', obi_exclude_woocommerce_products_from_search');
Edit:
To exclude multiple post types from the search, you can use a code like this:
/* LOOP POST TYPES */
add_action( 'register_post_type_args', 'mws_loop_post_types', 1, 2);
function mws_loop_post_types( $args, $post_type ) {
$mws_post_types = array('sfwd-courses', 'sfwd-lessons'); // Add the slug for as many post types as you want.
// EXCLUDES FROM SEARCH ONLY THE SPECIFIC POST TYPES IN THE ARRAY mws_post_types
for ($i = 0; $i <= (sizeof($mws_post_types)) ; $i++) {
if( ($mws_post_types[$i]) == $post_type ){
$args['exclude_from_search'] = false;
}
}
return $args;
}