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 );
}
}
}
- 'page' will exclude the regular WordPress pages from the search results.
- 'projects' is a custom pot types. So it will exclude the project pages from the search results.
- 'product' will exclude the WooCommerce products from the search results.
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.