How to hide WordPress content from search results

While it is easy to drop in some code to hide content from search results, it can have some unintended consequences because WordPress uses the same search query loop for both frontend and backend searches.

Hide content universally

To hide content on both the front and backend, we can use the following code:

function prefix_exclude_from_search( $query ) {
	if ( $query->is_search ) {
		$query->set( 'post__not_in', array( 1, 2, 3 ) );
	}
	return $query;
}
add_filter( 'pre_get_posts', 'prefix_exclude_from_search' );

Notice on line 3 there is an array. This array contains the IDs of content that will be hidden from search results. We can change these IDs to match whatever content we want to hide. So if we wanted to hide a page with an ID of 15 and a post with an ID of 1283, our array should look like this: array( 15, 1283 ).

Hide content on frontend

In this case, we only want to modify the search if we’re not in WordPress admin dashboard. This can be done by adding ! is_admin() && to the if statement in the code above. Here’s what it looks like:

function prefix_exclude_from_frontend_search( $query ) {
	if ( ! is_admin() && $query->is_search ) {
		$query->set( 'post__not_in', array( 1, 2, 3 ) );
	}
	return $query;
}
add_filter( 'pre_get_posts', 'prefix_exclude_from_frontend_search' );

Hide contend on backend

To only hide content on the backend, we just need to remove the exclamation point (!) from the if statement we added for frontend exclusion. Now our code should look like this:

function prefix_exclude_from_backend_search( $query ) {
	if ( is_admin() && $query->is_search ) {
		$query->set( 'post__not_in', array( 1, 2, 3 ) );
	}
	return $query;
}
add_filter( 'pre_get_posts', 'prefix_exclude_from_backend_search' );

Other considerations

Some queries run as AJAX calls, which might have unexpected results using the code above since we’re not explicitly handling AJAX calls. How those should be handled will depend on the circumstances of the call and what you’re trying to accomplish, which is beyond the scope of this post.

Posted in

Leave a Comment

Your email address will not be published. Required fields are marked *