How To Exclude Pages / Posts In A WordPress Search / Query


09.03.2011

How To Exclude Pages / Posts In A WordPress Search / Query

When perform a WordPress search, sometimes you don’t want to have search results that displays every posts and page. There is way to execute a more filtered search in the frontend, by adding a filter to the query of WordPress and exclude the according posts or pages of the search.

The pages and posts can be excluded by their ID given to an array and omit some of them. In the first code 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 desire to have the subpage of a page excluded, 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’ );

Summing up, this one of the many possibilities to exclude posts and pages in the WordPress search.

WordPress

Tags: query, pages, search, page, wordpress, posts, array, filter, is_search, is_admin, exclude, pre_get_posts, fb_search_filter, setpost__not_in, fb_search_filterquery, function, add_filter, excluded, return, post, subpage, desire, childrens, childrensi, sizeofchildrens, summing, many, possibilities, fori, echo