search ]

Exclude Pages from WordPress Search Results

To exclude pages from search results, add the following code to your functions.php file. You can also limit search to a specific Post Type by changing “post” on line 7 to the slug of the Post Type you want to display.

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

add_filter('pre_get_posts','filter_pages_from_search');

Conversely, to make WordPress search pages as well as posts, use this code:

function filter_pages_from_search($query) {
    if ($query->is_search) {
        $query->set('post_type', array('post', 'page'));
    }
    return $query;
}

add_filter('pre_get_posts','filter_pages_from_search');

For more on controlling WordPress search visibility, see Prevent Search Engines from Indexing Search Results.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo