Skip to main content Accessibility Feedback

How to exclude pages from Search in WordPress

Up until a few weeks ago, if you searched for common terms like “mobile,” “jquery,” or “design” on this site, my about page would show up in the results. It was weird and not really relevant to what a person would typically be looking for when using search.

Fortunately, there’s a pretty easy way to configure your search results so that only posts (not pages) show up. Just add this snippet of code, courtesy of C. Bavota, to your functions.php file…

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

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips