10 Useful Snippets for Improving WordPress Search

It is no secret that the standard search within WordPress is not the greatest. The problem is that WordPress takes your search term far too literally.

In this post, we have ten really useful WordPress search code snippets that will help improve the search accuracy for your readers. ust copy and paste.

You might also like these useful .htaccess snippets & hacks, these WordPress SQL Query Snippets, or these snippets that make WordPress user-friendly for your clients.

How To Exclude Posts or Pages from WordPress Search Results

If you would like to be able to control which posts or pages should be excluded from WordPress search results, all you have to do is copy and paste the code below into your functions.php file.

In this snippet, posts with the IDs 0 and 1 will be excluded. Edit accordingly to suit your needs.

function SearchFilter($query) {
    if ($query->is_search) {
    return $query;


WordPress Drop-Down Category Search Form

A useful function you could give to your WordPress search would be to allow your readers to filter the search results by targeting a specific category. This can be achieved by using a simple drop-down containing all of the category titles.

All you have to do is replace the standard WordPress search form (found within the searchform.php) with the snippet below:

<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" /> 
    in <?php wp_dropdown_categories( 'show_option_all=All Categories' ); ?> 
    <input type="submit" id="searchsubmit" value="Search" />

Dynamically Search WordPress Categories & Child Categories Only

This search form snippet could be useful within the category archive to allow your readers to search the child categories from any given parent category.

In this snippet, all child categories from category ID 1 will be searched. Edit accordingly to suit your needs.

</form method=”get” id=”searchform” action=”</?php bloginfo(‘home’); ?>/”>
   </div id=”search”>
      </input type=”text” value=”Search… ” onclick=”this.value=”;” name=”s” id=”s” />
      </?php $categories = get_categories(‘child_of=1′);
         $catlist = ”;
         foreach ($categories as $cat) {
         $catlist.= $cat->cat_ID.’,';
      </input type=”hidden” name=”cat” value=”</?php echo “$catlist”?>” />
      </input name=”" type=”image” src=”</?php bloginfo(‘stylesheet_directory’); ?>/styles/</?php echo “$style_path”; ?>/search.gif” value=”Go” class=”btn” />
   </!–/search –>

Search a Specific WordPress Post Type

WordPress gives you the ability to search specific post types by using this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  return $query;

// This filter will jump into the loop and arrange our results before they're returned

Display the Number of Search Results Returned

If you would like to show your readers how many results have been found per search term, you could use this helpful snippet.

Open search.php and locate the following:

<h2 class="pagetitle">Search Results</h2>

And replace it with this code:

<h2 class="pagetitle">Search Result for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span class="search-terms">'); echo $key; _e('</span>'); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>

Source: problogdesign.com →

Highlight WordPress Search Terms with jQuery

To help make your search results that little bit clearer to your readers, you could use this snippet which will highlight the searched term within the results.

Copy and paste the following code into your theme’s functions.php file:

function hls_set_query() {
  $query  = attribute_escape(get_search_query());

  if(strlen($query) > 0){
    echo '
      <script type="text/javascript">
        var hls_query  = "'.$query.'";

function hls_init_jquery() {

add_action('init', 'hls_init_jquery');
add_action('wp_print_scripts', 'hls_set_query');

And then add this code into your header.php file, just before the /head tag:

<style type="text/css" media="screen">
    .hls { background: #D3E18A; }
  <script type="text/javascript">
    highlight: function(search, insensitive, hls_class){
      var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
      return this.html(this.html().replace(regex, function(a, b, c){
        return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "</strong>";
    if(typeof(hls_query) != 'undefined'){
      $("#post-area").highlight(hls_query, 1, "hls");

Disable WordPress Search

If you are looking for a way to disable all of WordPress’ search functionality, you could use this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

function fb_filter_query( $query, $error = true ) {

	if ( is_search() ) {
		$query->is_search = false;
		$query->query_vars[s] = false;
		$query->query[s] = false;

		// to error
		if ( $error == true )
			$query->is_404 = true;

add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Make your WordPress Search Results Unlimited

Sometimes you may not want your search results to be limited by the confines of the standard WordPress Loop. This snippet allows your search to return unlimited results.

In search.php you can add the following code above the loop for this functionality.

First of all find this code within search.php:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

And then add this code:

<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

Implement Google AJAX Search API

Google provides an awesome method in which you can use their search for your own site: the Google AJAX Search API. In this advanced tutorial you will be shown how to implement this awesome API within your own website. Google's AJAX Search API requires that you sign up for an API key, you can get it here: Google AJAX Search API.

Create an Ajax-based Auto-completing Search Field for WordPress

When someone starts to type with the search field they will be presented with a drop-down box offering suggestions. This tutorial will show you how to implement thsi on your own site.


  • dcpanganiban

    Have you resolve this issue ? I am trying to figure ow to remove the + sign

  • Ppp

    Thanks so much for posting the code fr “WordPress Drop-Down Category Search Form”
    I have spent most of the day installing and uninstalling plugins to try to get this incredibly simple function.

    Someone should make a plugin of this code and save us poor wretches wasting our precious time looking for it. Alternatively WordPress should just make searching categories an option within their existing searchbox.

    Thanks again.

  • Matthew

    Most sites like this assume that you already understand lots about php so it makes it difficult for beginners.  Thanks for making it simple, I found “WordPress Drop-Down Category Search Form” extremely easy to impliment.  I have just been experimenting with custom post types and taxonomies, would it be possible to modify the ” WordPress Drop-Down Category Search Form” Code to create a custom search form for the various catagories inside my custom post type?

    Thanks again!

  •  hello, i just wanna ask if you could provide a code that will trim and show only the text beetween theText Here .. also, a code that will show the text which has a beginning of a word ‘Price’

    e.g: post text… Price: $23.99…text text…

    the output will be, $23.99

    thanks in advance, cheers!

  • Dojodesign

    Dynamically Search Categories and Child Categories Only doesn’t work. You should check your copy-pasted codes. Looks like WPgarage haven’t checked it either ;)

  • webapptester

    Nice and very handy, thanks a lot! :)

  • Ahmed Abbas

    Thanks. It is very useful.

  • Tio nélio Do Rincão

    very wonderfull, tks dude!

  • Nico

    Exclude posts doesn’t work on 3.8…it’s a shame any workaround without plugins?

  • Mike

    When I cut and paste the code for “How To Exclude Posts or Pages from Search Results” I get a fundamental PHP failure? Any clues as to why?

  • The issue with using the `prefix_search_filter` WP Filter is that this impacts search in both the frontend and backend. If you’re not careful, this query will fire when using the Search functionality in the Dashboard as well. Here’s an example of how to avoid this issue: https://gist.github.com/lukad03/bca0c891f6c1d5f7289919efb6d48a25

  • Chandwani Gaurav

    Can you please let me know how to modify search based on parent child relation of taxonomies. For example If I am enter the child category name then it should show first the parent category then child category based on searched value then products related to child category.