How To Exclude Posts and Pages in WordPress Search

Sometimes we don’t want to display every page and post in search results. Today I like to explain you how to add filter to the search. For this I have added a filter to the search query of WordPress and exclude posts or pages as per my requirement of the search result.

We can exclude posts and pages by their ID, which we will give to an array and so exclude several posts and pages.

In my first code example the ID’s 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 my_search_filter($query) {

    if ( !$query->is_admin && $query->is_search) {
        $query->set('post__not_in', array(21, 39) ); // id of page or post
    }

    return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );

If you like to exclude the subpage of any page, then you can add below code.

// search filter
function my_search_filter($query) {

    if ( !$query->is_admin && $query->is_search) {
        $pages = array(21, 39); // id of page or post
        // find children to id
        foreach( $pages as $page ):
            $childrens = get_pages( array('child_of' => $page, 'echo' => 0) );
        endforeach;
        // 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', 'my_search_filter' );

There are too many possibilities to do this but I think this is a useful post for you.

Leave a Reply

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