How to Exclude Posts / Pages from default WordPress Search

By default WordPress search query running through published Posts and Pages by default. But according to some requirements you need to exclude some Pages or Posts from search query. Lets say you want to exclude all the Pages from search query and you need to run search query through Posts only. So, how you going to do that. You can either use function file or if you’re customizing through a site specific plugin. Both are acceptable. Here is the magic.

// Search Filter
function nerodev_search_filter( $query ) {
    if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
        $query->set( 'post_type', 'post' );
    }
}
add_action( 'pre_get_posts', 'nerodev_search_filter' );

This will exclude the all Pages from WordPress default search and run search query through Posts only.

How to exclude specific Pages from WordPress Search

We have gone through the Post filter and here we go with the Pages. Sometimes you want keep some pages away from the search. No worries here is the way to do so. It is not much difference from the above.

// Search Filter
function nerodev_search_filter( $query ) {
    if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
        $query->set( 'post__not_in', array( post, ids, to, exclude ) );
    }
}
add_action( 'pre_get_posts', 'nerodev_search_filter' );

Inside the array you need to put all the page ids you want to exclude from default WordPress search. Keep the comma separated. For example I am assuming you need to exclude following pages from the search.

array( 134456, 123789, 456732 )

Like above you need to pass you page IDs to exclude the pages from default WordPress search.

Hope this is helpful to you.

You may also like...

Leave a Reply

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