Family Encyclopedia >> Electronics

How to Exclude Pages from WordPress Search Results for Better Relevance

As experienced WordPress developers, we've seen how default search results often mix posts and pages, diluting relevance. Users typically hunt for blog content, not static pages. Here's a proven method to refine your site's search, showing only posts for a cleaner, more targeted experience.

How to Exclude Pages from WordPress Search Results for Better Relevance

Add this reliable code snippet to your theme's functions.php file or a custom plugin:

function wpb_search_filter( $query ) {
    if ( ! is_admin() && $query->is_search ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wpb_search_filter' );

This code hooks into WordPress's pre_get_posts filter. It checks for frontend searches only (skipping admin areas), then limits results to posts by setting post_type to post, effectively excluding pages.

To reverse it and show only pages, change 'post' to 'page'.

This tweak has helped countless sites improve user satisfaction and engagement. For even more power, explore our roundup of the best WordPress search plugins.

If this was useful, subscribe to our WordPress YouTube channel for video tutorials. Follow us on Twitter and Facebook for tips and updates.