Limit Your WordPress Search Results

We all know the default WordPress search function isn’t very great or at least not as good as Google 🙂 , but there are a few tricks out there to help improve the search results. This post will show you different methods of limiting your search results to specific posts types or categories and  how to change the default number or search results per page.

Limit WordPress Search Results By Category

Here are a few methods you can use for limiting your search results by category which can be very useful for sites like WPExplorer.com which has sections such as themes, plugins and the blog.

1. Using A Hidden Input Field In Your Searchform.php

This is the method I currently use on WPExplorer.com so when people search the main site they will only get search results from the “WordPress Themes” category. All you need to do is add a hidden input to your searchform.php with an id of “cat” and the category id for the value.

A basic searchform.php

<form method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
    <input type="text" size="16" name="s" value="Search"  />
    <input type="submit" value="Go" />
</form>

Add the following to limit to the category with an ID of 5

<input type="hidden" name="cat" id="cat" value="5" />

Full Code

<form method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
    <input type="hidden" name="cat" id="cat" value="5" />
    <input type="text" size="16" name="s" value="Search"  />
    <input type="submit" value="Go" />
</form>

2. Adding A Query Statement To Your Search.php File

Another useful method for limiting your search results to specific categories is to add a query to your search.php file right before the if statement.

Including Categories To The Search

By using positive ID’s in the query you can define which categories you want to show in your search results (show categories with ID’s 1,2 and 3).

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
query_posts( "s=$s&paged=$paged&cat=1,2,3" );
?>

Excluding Categories From The Search

Alternatively you can use negative ID’s to exclude certain categories from your search page (exclude the category with an ID of 7)

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
query_posts( "s=$s&paged=$paged&cat=-7" );
?>

Exclude Pages From Your Search Page

Below are a couple ways you can limit your search results to exclude pages from the results and show only posts.

Using a Function

Simply insert the following function to your functions.php file

/ Remove pages from search results
function exclude_pages_from_search($query) {
    if ( $query->is_main_query() && is_search() ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter( 'pre_get_posts','exclude_pages_from_search' );

Using A Conditional In Your Search.php File

Another way to remove pages from your search.php file is to insert a conditional in your search.php file right after “while ( have_posts())”. This isn’t recommended if you are using a 3rd party theme because if you update the theme in the future you will lose your edits, if it’s your own custom theme then it’s fine.

<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
   // Exclude pages from the loop
   if ( is_search() && ( $post->post_type=='page' ) ) {
       continue;
   } ?>

Exclude a specific page or pages

You can also exclude specific posts/pages from your search results pages on their ID’s by using the following code added in the functions.php file. Simply alter the array of ID’s to include the ID’s of the pages or posts you wish to exclude.

// Exclude specific posts/pages from search
function exclude_pages_from_search($query) {
	if ( $query->is_main_query() && is_search() ) {
		$exclude_ids = array( 7, 19 , 21 ); // Array of the ID's to exclude
		$query->set( 'post__not_in', $exclude_ids );
	}
	return $query;
}
add_filter( 'pre_get_posts','exclude_pages_from_search' );

Limit Search To Post Type

One of the reasons to use Port Types in WordPress is because you don’t want these in your feed or main wp loop, that is why they are perfect for things like sliders, testimonials, services…etc. However, your custom posts may still appear in your search results page.

1. Exclude A Custom Post Type From Search Results

All you have to do to exclude custom posts from search results is to set the following argument when defining your custom post (more info):

'exclude_from_search' => true

2. Using A Hidden Field In The Search Form To Show Only Posts From A Specific Custom Post Type

Alternatively you can use a hidden field in your search form the same way you did for limiting categories if you want to set up an advanced search form which will only search through the specified custom post type.

<input type="hidden" name="post_type" value="portfolio" />

This extra field would go inside your searchform and you would simply replace where it says “portfolio” with your own custom post type name. This method is great if you have a certain section on your site that uses custom post types and you want users to be able to search through those specific posts only.

Changing The Number Of Results Per Page

By default WordPress uses the number defined under Settings > Reading (blog pages show at most…) to define how many results appear on the search results page. If you would like to show more, less or infinite results on your search page you can do so using the following code:

// Alter search posts per page
function myprefix_search_posts_per_page($query) {
    if ( $query->is_search ) {
        $query->set( 'posts_per_page', '10' );
    }
    return $query;
}
add_filter( 'pre_get_posts','myprefix_search_posts_per_page' );

This code would go in your functions.php file. Preferably in your child theme if working with a theme from another developer. The code will set your search results to “10” per page. You can change the number to whatever you want. For making your search results unlimited use -1.

Advanced/Better Search

WordPress by default searches based on any content inside your posts and pages. It would be possible to alter the way the search works via functions but it’s fairly complex so if you want to alter the way the search actually works (what it searches for) you may consider instead using a plugin such as the ‘WP Extended Search” plugin. Click the banner below to check it out or search for it in your WordPress dashboard under Plugins > Add New.

wp-extended-search

This plugin will allow you better control the default search if you want to search by meta, categories, tags, terms, title…etc. You can include or exclude certain post types from search, exclude posts that are older then a specific date, alter the number of items displayed on the search results and more!

AJ Clarke
Post Author: AJ Clarke

Hey. My name is AJ and I am the boss around here. I own and operate WPExplorer. A website dedicated to everything I love about WordPress.

Disclosure: This page contains external affiliate links that may result in us receiving a comission if you choose to purchase said product. The opinions on this page are our own. We do not receive payment for positive reviews.
Got something to say? Join the discussion.
  1. Hi, I am trying to use "Using A Hidden Field In The Search Form To Show Only Posts From A Specific Custom Post Type". By using the hidden field input type, the search is limiting to the custom post, but the problem is it is displaying "all" my custom post types instead of displaying my custom post types based on the keyword search. How can I solve this? Any help is greatly appreciated. Thanks
    • AJ Clarke says:
      AJ Clarke
      Not quite understanding what you are saying. You say "the search is limiting to the custom post" but then you say "it is displaying “all” my custom post types" - seems contradictory. You should check out my Moderno theme on the search page see how I did the drop-down, might help you - view demo here.
      Admin
  2. Thanks for your response AJ Clarke. Let me give an example of what I was trying to say, I have 5 posts in my custom post type "events". If I do a keyword search for "mary" the result should display 2 posts,since the keyword is present in only those two posts, but instead, it is displaying all 5 posts.
    • AJ Clarke says:
      AJ Clarke
      That's not supposed to happen...Same issue when searching regular posts?
      Admin
  3. No, Only in custom post types.
  4. Albuquerque Wordpress says:
    Great article- I was looking for a way to exclude specific pages from the search result- Would you have a solution? Thanks
    • Kyla
      It's mentioned on the post, you probably just missed it.
      Admin
      • Nick Normal says:
        I see the code for restricting Pages but not a specific page; i.e. I have Page 1, Page 2, Page 3 and want to only exclude Page 2 from results - is this mentioned above?
        • AJ Clarke says:
          AJ Clarke
          I just updated the post to include a new snippet for excluding specific posts or pages. Good idea!
          Admin
  5. Hi AJ i would like to know is it possible to limit the search like 1 visitor/user/member able to search 10 times in my website?
    • AJ Clarke | WPExplorer says:
      AJ Clarke | WPExplorer
      I honestly am not sure how you would be able to do this. You would maybe create a new user custom field and store a counter for the data everytime they run a search query and then use this counter as a conditional on the search page - http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields - not sure if that's a good way or how it would work per-se, but maybe it's a nice start?
      Admin
  6. thanks AJ
  7. henrywrightdotmeHenry says:
    Hi AJ, would the hidden field approach work for BuddyPress member search too? Currently the BuddyPress member search searches through the whole member profile (name, location, profession). I want to limit the search to search through member names only.
    • AJ Clarke | WPExplorer says:
      AJ Clarke | WPExplorer
      I'm not sure. I haven't messed too much with BuddyPress.
      Admin
  8. Amazing article, super useful. I just used "Changing The Number Of Results Per Page" and it worked.
  9. Thanks, worked great to limit searches to only posts!
  10. Hi AJ, This is an old post, but just wanted to say found it very useful! is there a way to lmit search scaping? For example random bots are trying to scrape the site for content? Tried bad behavior and setup some rules, but they only helped a little. They seem to be using randoms ips so blocking their ips doesn't help either.
    • AJ Clarke says:
      AJ Clarke
      Humm...if your concern is SEO you could add a nofollow rel tag to your search page maybe?
      Admin
  11. tfadonovan says:
    Hello. I have hundreds of pages that I would like to create a search bar for that will only pull the names of specified pages. Example: I have player pages for sports, so Im looking for a search bar that produces one result when a specific name is searched, not anything holding that tag. Hopefully that makes sense.
    • AJ Clarke says:
      AJ Clarke
      This is a great question I actually found a very good answer on stackexchange which I suggest you take a look at rather then me giving you essentially the same answer. I hope this helps!
      Admin
  12. Swapnil Thakkar says:
    Hi AJ Clarke, the wp search searches from everywhere in the post. I want to exclude content from search. I want my site to search from only titles, categories and tags. I searched a lot on the Google, but hard luck. And I found this page, so curious if you can help something. Thank you.
    • AJ Clarke says:
      AJ Clarke
      That is more complex if you want to use custom code I added a new section at the bottom of the post if you want to check it out.
      Admin
  13. sarrahabl says:
    Hi there, I was wondering if there is a way to set up a search function that is limited to looking only at posts and not pages on my wordpress site? Is this possible?
  14. francescapinky4 says:
    Thanks Clarke !!

Leave a Reply