Modifying WordPress Search Results, Excluding Pages

When developing a single page website, allowing the client to customise each individual section of the page by editing them as sub-page. Once this was working, a problem appeared when testing the search box by all these pages showing up in the results.

This article will explain how to tailor WordPress search results.

Modifying the pre_get_posts filter

In order to fix this I had exclude these pages from the WP_Query on the results page only. To do this we had to use the pre_get_posts filer, this allowed me to modify the search query and not target the specified page id’s.

The following code should be added to your functions.php in your theme directory and you should change (25,27,29,31,33) to the page id’s you wish to exclude from the search results.

function jc_remove_landing_pages($query) {
    // check to see if search
    if ($query->is_search) {
        // only search the paeg post type
        $query->set('post_type', 'page');
        // dont search these pages
        $query->set('post__not_in', array(25,27,29,31,33));
    }
    return $query;
}
 
add_filter('pre_get_posts','jc_remove_landing_pages');


Liked this article? help spread the word.