Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

How to Limit Your WordPress Search Results

Last updated on:

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.

How to 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 role="search" method="get" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
	<label class="searchform-label">
		<span class="screen-reader-text"><?php esc_html_e( 'Search', 'text_domain' ); ?></span>
		<input type="search" class="searchform-input" name="s" placeholder="<?php esc_attr_e( 'Search', 'text_domain' ); ?>">
	</label>
	<button type="submit" class="searchform-submit"><?php esc_html_e( 'Submit', 'text_domain' ); ?></button>
</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 role="search" method="get" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
	<label class="searchform-label">
		<span class="screen-reader-text"><?php esc_html_e( 'Search', 'text_domain' ); ?></span>
		<input type="search" class="searchform-input" name="s" placeholder="<?php esc_attr_e( 'Search', 'text_domain' ); ?>">
	</label>
	<input type="hidden" name="cat" id="cat" value="5">
	<button type="submit" class="searchform-submit"><?php esc_html_e( 'Submit', 'text_domain' ); ?></button>
</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' ) ?: 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' ) ?: 1;
query_posts( "s=$s&paged=$paged&cat=-7" );
?>

How to Exclude Pages From Your Search Results?

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:

/**
 * Set search results post types.
 */
function wpexplorer_exclude_pages_from_search( $query ) {
	if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) {
		$post_types = [ 'post' ];
		$query->set( 'post_type', $post_types );
	}
}
add_filter( 'pre_get_posts','wpexplorer_exclude_pages_from_search' );

Make sure to modify the function to change the $post_types variable to include all the post types you want to display in your search results.

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.

if ( have_posts() ) : while ( have_posts() ) : the_post();
   // Exclude pages from the loop.
   if ( 'page' === get_post_type() ) {
       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 pages from search results by ID.
 */
function wpexplorer_exclude_pages_from_search( $query) {
	if (  ! is_admin() && $query->is_search() && $query->is_main_query() ) {
		$exclude_ids = [ 7, 19 , 21 ]; // Array of the ID's to exclude.
		$query->set( 'post__not_in', $exclude_ids );
	}
}
add_filter( 'pre_get_posts', 'wpexplorer_exclude_pages_from_search' );

How to Limit Search Results by 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 via the wp_register_post_type function.

'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 search form 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.

How to Change the Number of Search Results?

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 wpexplorer_search_posts_per_page( $query) {
    if ( ! is_admin() && $query->is_search() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', '10' );
    }
}
add_filter( 'pre_get_posts', 'wpexplorer_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. Or utilize a plugin like Toolset Search to add pagination to your results.

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.

WP Extended Search

Once such option is the WP Extended Search plugin. This plugin allows 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 than a specific date, alter the number of items displayed on the search results, customize the ordering and more!

Ivory Search

Another search plugin you may want to consider is Ivory Search. This plugin allows for custom search forms with options to configure each form separately. So you can create a custom search for a specific post type like your portfolio, or create a search for you homepage that searches everything on your site excluding your staff. There are options to search based on posts, pages, products, taxonomies, custom fields, author and more.

Relevanssi

Relevanssi Better Search Plugin

And the last plugin we’d like to share is Relevanssi. By far the most advanced option, Relevanassi offers many features to improve your WordPress site search function including settings to limit search results. You can easily restrict searches using the plugin’s indexing options. Simply choose what post types and taxonomies you’d like to index and/or exclude from your search, select category restrictions/exclusions, add specific post id exclusions (like your checkout page perhaps) and much more. There is also a premium version of this plugin if you’re looking for even more features as well.

Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

46 Comments

  1. Ashish

    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

      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.

  2. Ashish

    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

      That’s not supposed to happen…Same issue when searching regular posts?

  3. Ashish

    No, Only in custom post types.

  4. Albuquerque Wordpress

    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.

      • Nick Normal

        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

          I just updated the post to include a new snippet for excluding specific posts or pages. Good idea!

  5. Peter

    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?

  6. Peter

    thanks AJ

  7. henrywrightdotmeHenry

    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

      I’m not sure. I haven’t messed too much with BuddyPress.

  8. stempi

    Amazing article, super useful. I just used “Changing The Number Of Results Per Page” and it worked.

  9. Tigre

    Thanks, worked great to limit searches to only posts!

  10. Tom

    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

      Humm…if your concern is SEO you could add a nofollow rel tag to your search page maybe?

  11. tfadonovan

    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

      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!

  12. Swapnil Thakkar

    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

      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.

  13. sarrahabl

    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

    Thanks Clarke !!

  15. Chris DiMattei

    So how do I go about creating a unique search form, that operates independently from the “whole site search form”, that is programmed to limit the results to posts of a single category? And I would like to do this in such a way that I don’t edit my theme files to achieve this, because I don’t want to have to redo this effort, every time there is an update to my theme. Is there a way that I can achieve this with a search form shortcode that is in some way customized to limit the search results to posts of a single category. Lastly, I don’t want to introduce a drop-down list of categories, because I don’t want my readers to have to choose the category. The category will be chosen for them by the nature of the page they are visiting. Thanks.

    • AJ Clarke

      It sounds like you may want to locate an “AJAX” search plugin that you can use to add a search to a page and when the user searches the results are shown on the same page without taking you to the default WordPress search page.

  16. Investeach

    AJ, thanks for the article and your support of WordPress. I have a few sites based on it and am really enamored of the looks that can be achieved with the amazing themes available as well as the enhancements available through the amazing plug-ins that are out there. One example is my too-infrequently-posted-to blog Tommentary.com.

    My question about your article: If one of the suggested solutions is implemented, does this change the search function for the whole site? I am moving a site (Investeach.com) I had on Joomla over to WordPress. I have a terms glossary on the Joomla site that I want to just move over as posts assigned to a category named Glossary so I can avoid the overhead and special post types I would have with a glossary plug-in. My hope was to have a Glossary page on the new WordPress-based site with a search that is restricted to just the Glossary category. The search available on the Main Menu and anywhere else on the site would be unrestricted. Thanks in advance for any assistance you could provide.

    • AJ Clarke

      Hi,

      So basically you want to create a custom searchform on the Glossary page like the suggested implementation #1. And you should migrate all your Glossary posts into a Custom Post type in WordPress so you can setup a custom page to display them and filter them.

  17. williamslyd

    Great post, thanks. I’m trying to display a search bar at the top of each of my category pages but I want to limit the results to only posts in that category. Is that possible?

    • Kyla

      Yes, it’s very easy. Just use the first method mention in the post where you use the hidden field and “cat” as the name but for the value instead of using “5” use get_query_var('cat') (inside PHP tags of course).

  18. Darshan Saroya

    In default search widget, I want to exclude on CPT results and allow other. Rejected CPT have another search form. I Just want to show that’s CPT result only with custom search form. How can I do this?

    • Kyla

      You need to use the hidden field method as mentioned above. What you can do though is instead of using the search widget just use a text widget with the HTML for your form added in there.

  19. I want to make my search result(pages only) clickable and linked to the page I want to visited, any suggestions on the matter ?

    • AJ Clarke

      Sorry I am not sure what you mean, can you explain?

  20. Radu G.

    Hello.
    Everybody is talking about the results from the search, but there is somebody that can’t tell how id works in back? For example if I check to search only for one category, can WP do that? and not go truth all database rows and to search for post only in that category in database?
    This is very important for the server and search speed….

    • AJ Clarke

      In the database posts are not organized into different rows depending on the category so I don’t believe searching for a post within a specific category would actually speed things up. Even custom post types are all located within the wp-posts table so using different post types wouldn’t speed things up either. If speed is a huge concern I would recommend not using WP search. The WP search is pretty crappy anyway and there are way better services out there you can use such as Algolia or Google site Search, that’s what I would recommend. Although if you have a good webhost and you don’t have millions of posts the WP search should alway be fast (test ours).

  21. Phalancs

    Wow AJ, again you saved my life! WPExplorer is the best! Wow.

  22. Charles Oliveira

    Man, you are amazing!
    Big hug from Brazil.

    Your code save my life 😀

  23. Shane

    Awesome thanks! Before this, get_search_query() was showing pages and CPTs as well!

    Now it just shows posts 🙂

  24. VJ

    Hi AJ,
    Bookmarked this valuable resource.

    Here is a scenario that I came across recently:

    How do I create a search form that would only show results from child pages of a page with a page ID 3913?

    Thanks,
    VJ

    • AJ Clarke

      Hi,

      For this you would probably want to add a hidden field to your search form to pass to the query, something like this:

      <code><input type="hidden" name="parent_page" value="3913" /></code>

      Then you can hook into pre_get_posts to check for this query parameter. Example:

      add_filter( 'pre_get_posts', function( $query ) {
      	if ( $query->is_search() && array_key_exists( 'parent_page', $_GET ) && $query->is_main_query() && ! is_admin() ) {
      		$parent_page = $_GET['parent_page'];
      		$child_pages = array();
      		$get_child_pages = get_pages( array(
      			'child_of' => $parent_page,
      			'echo'     => 0,
      		) );
      		if ( is_array( $get_child_pages ) ) {
      			foreach ( $get_child_pages as $page ) {
      				$child_pages[] = $page->ID;
      			}
      		}
      		$query->set( 'post__in', $child_pages );
      	}
      } );
  25. Andy Globe

    Thanks. This worked for me. I wanted to exclude gallery appears in search results and this code does exactly what I need. Thanks

  26. Andy Globe

    Great articles – this was what I need and very helpful. Thank you for publishing.

  27. Logarik

    Thanks for ur sharing. It’s useful for me – I needed to keep pages from my search results. This was helpful!

  28. Jak wykonac

    This is what I was looking for. I wanted to exclude 1 category from the search results. There is no such feature inside wordpress itself. Now I know how to deal with it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.