Exclude Pages From WordPress Search Results

[ad_1]

By default, WordPress displays all of your blog’s pages in search results along with blog posts. But on a specific project you may want to exclude pages from WordPress search results to make your search more relevant and less crowded. After all, most of the time, your readers want to find interesting posts, not pages with boring legal stuff, terms and the like.

Previously we have shown you how to limit your search results for specific post types and in this article we are going to show how you can easily modify search query to exclude pages from search results and show results from blog posts only.

Just add the following code snippet to your theme’s functions.php file and let WordPress search through blog posts only.

// exclude pages from wordpress search results
function wcs_search_from_posts( $query ) {
    if ( $query->is_search && !is_admin() ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wcs_search_from_posts' );

Similarly, you could also exclude blog posts from your search results. For a website have mostly WordPress pages and does not actively use blog posts functionality, following code snippet will be very helpful. This code snippet will restrict WordPress to search from pages only and therefore show page in search results.

// exclude posts from wordpress search results
function wcs_search_from_pages( $query ) {
    if ( $query->is_search && !is_admin() ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wcs_search_from_pages' );
[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads