Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Exclude WordPress Pages From Search Results

There are times when you'll want to set up a WordPress page for whatever reason, but you don't want the page to be included in WordPress search results. This snippet will enable that feature.

Remove All Pages from Search Results

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
    Exclude WordPress Pages from appearing in Search Results
4
    http://www.beliefmedia.com/code/wp-snippets/exclude-wp-pages-search-results
5
*/
6
 
7
 
8
function beliefmedia_search_filter($query) {
9
  if ($query->is_search) {
10
   $query->set('post_type','post');
11
  }
12
 return $query;
13
}
14
add_filter('pre_get_posts','beliefmedia_search_filter');

This function will search for the post type of post. However, you could alter the post type to pages if you wanted to only render pages in the search results.

Remove Specific Pages or Posts from Search Results

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
    Exclude WordPress Pages from appearing in Search Results
4
    http://www.beliefmedia.com/code/wp-snippets/exclude-wp-pages-search-results
5
*/
6
 
7
 
8
function beliefmedia_custom_search_filter($query) {
9
  if ( !$query->is_admin && $query->is_search) {
10
   $query->set('post__not_in', array(25, 45) ); // ID of pages or posts
11
  }
12
 return $query;
13
}
14
add_filter( 'pre_get_posts', 'beliefmedia_custom_search_filter' );

The array (25, 45) on line 3 contains either the page or post ID that you don't want to appear in search results. In this case, it's the page/post ID's of 25 and 45.

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment