How to Exclude Pages from WordPress Search Results?

By default, WordPress Search feature displays published posts and published pages in search results. Often when users are looking for something in a blog, it is most likely a post rather than a page. In this article, we will show you how to make your search more relevant and less crowded by excluding pages from WordPress search results.

Add the following code in your theme functions.php

//Exclude pages from WordPress Search
if ( !is_admin() ) {
    function webtut_search_filter( $query ) {
        if ( $query->is_search ) {
            $query->set('post_type', 'post');
        }
        return $query;
    }
    add_filter('pre_get_posts', 'webtut_search_filter');
}

This code removes all post types from displaying in your search results and only returns results for posts.

Leave a Reply

%d bloggers like this: