wpblooms - WordPress Support

Published:

How to exclude Pages, CPTs, and WooCommerce Products from WordPress search results?

WordPress

One of my friends asked me, how she can exclude Pages, CPTs, and WooCommerce products from the Elementor search results except for the regular posts.

I didn’t face this issue/idea in the past. So I Google the issue and found the code on cssigniter.com. A warm thanks to Nik.

Here is the extended code.

I am not a coder. So I am not 100% sure if it is correct or not the way I wrote it or extended it. It can be in different ways. But it works for me :).

				
					add_action( 'pre_get_posts', 'my_search_exclude_filter' );
function my_search_exclude_filter( $query ) {
if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
$searchable_post_types = get_post_types( array( 'exclude_from_search' => false ) );
$post_type_to_remove = 'page';
if( is_array( $searchable_post_types ) && in_array( $post_type_to_remove, $searchable_post_types ) ) {
unset( $searchable_post_types[ $post_type_to_remove ] );
$query->set( 'post_type', $searchable_post_types );
}
$post_type_to_remove = 'projects';
if( is_array( $searchable_post_types ) && in_array( $post_type_to_remove, $searchable_post_types ) ) {
unset( $searchable_post_types[ $post_type_to_remove ] );
$query->set( 'post_type', $searchable_post_types );
}
$post_type_to_remove = 'product';
if( is_array( $searchable_post_types ) && in_array( $post_type_to_remove, $searchable_post_types ) ) {
unset( $searchable_post_types[ $post_type_to_remove ] );
$query->set( 'post_type', $searchable_post_types );
}
}
}
				
			

Implementation

Process 1:

We have to add the code to the functions.php file. If you follow this method, I strongly recommend using a child theme.

Process 2:

If you don’t have or are not familiar with the child theme then you may use Code Snippets or WPCode plugin for adding the code.

Share on social media:

Need help with WordPress Development?

Need help with WordPress website development?

Need help with updating/editing website content?

Need help with updating (weekly) WordPress?

Need help with WordPress backup?

Need help learning WordPress?

Need help learning Elementor Pro?

What about

20% OFF?