I would like to remove our projects from the search bar results in WordPress. I have come across the following snippet to do so, however, this method is by listing all the post IDs. Is there a way to exclude all /projects/
at once?
function ss_search_filter( $query ) {
if ( !$query->is_admin && $query->is_search && $query->is_main_query() ) {
$query->set( 'post__not_in', array( 1, 2, 3 ) );
}
}
add_action( 'pre_get_posts', 'ss_search_filter' );
7
Since this is Divi, the Project post type is custom. You should be able to use the following filter. Note, there were some errors in the initial function specifically is_search()
and is_admin()
are $query
Object methods, so you should use the ()
to denote. Also, the $query
needs to be returned – or it won’t work as expected.
function ss_search_filter( $query ) {
// If the query is_admin() bail
if ( $query->is_admin() ) :
return $query;
endif;
// If the query is_search and is_main_query
if ( $query->is_search() && $query->is_main_query() ) {
// set the post type to only post types you want returned.
$query->set( 'post_type', ['page', 'post' ] );
}
// Return the query.
return $query;
}
add_action( 'pre_get_posts', 'ss_search_filter' );
1