Sometimes you don’t like to display every post and page on search results. Today I like to show you how to filter the search in your frontend. Therefore I add a filter to the query of WordPress and exclude the according posts or pages of the search.
We exclude posts and pages by their ID, which we will give to an array and so exclude several posts and pages.
In our first code example the IDs are set in the array. The filter is only working if it is the search is_search and if you are not ! in the backend is_admin.
// search filter
function fb_search_filter($query) {
if ( !$query->is_admin && $query->is_search) {
$query->set('post__not_in', array(40, 9) ); // id of page or post
}
return $query;
}
add_filter( 'pre_get_posts', 'fb_search_filter' );
If you like to exclude the subpage of a page, then you can add it to the ID.
// search filter
function fb_search_filter($query) {
if ( !$query->is_admin && $query->is_search) {
$pages = array(2, 40, 9); // id of page or post
// find children to id
foreach( $pages as $page ) {
$childrens = get_pages( array('child_of' => $page, 'echo' => 0) );
}
// add id to array
for($i = 0; $i < sizeof($childrens); ++$i) {
$pages[] = $childrens[$i]->ID;
}
$query->set('post__not_in', $pages );
}
return $query;
}
add_filter( 'pre_get_posts', 'fb_search_filter' );
There are many possibilities and I hope I was able to give you a starting point if you like to exclude posts and pages in your search.