Hide Pages from Search Results in WordPress

In WordPress by default both posts and pages are included in the Search Results, you can remove pages or posts for that matter and also include custom post types by using the action hook pre_get_posts.

In your functions.php add the appropriate snippet;

To remove pages from the search results add in…

<?php //<~ don't add me in
function wpb_remove_pages($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
add_action('pre_get_posts','wpb_remove_pages');

To remove posts from the search results add in…

<?php //<~ don't add me in
function wpb_remove_posts($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'page');
}
}
}
add_action('pre_get_posts','wpb_remove_posts');

To add in custom post types to the search results add in

<?php //<~ don't add me in
function wpb_add_cpt_search($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array('page', 'post', 'custom-post-type-name'));
}
}
}
add_action('pre_get_posts','wpb_add_cpt_search');
view raw add_cpt_search.php hosted with ❤ by GitHub

In the last code snippet we are passing in an array of different post types, just adjust the names of them to suit your needs.

Leave a Comment





%d bloggers like this: