10 Useful WordPress Search Code Snippets

It is no secret that the standard search within WordPress is not very accurate. The problem is that WordPress takes your search term far too literally, meaning, that if you were to type “search+code+wordpress” in to our search box above, it would return every post that contains those terms (in this case over 30 posts), even though we have no such post with in our database. So, in actual fact even though there are over 30+ results, our reader will never actually find what they are looking for. We have to improve this.

In this post we have 10 really useful code snippets that will help improve your WordPress Search functionality.

How To Exclude Posts or Pages from 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) {
        $query->set('cat','0,1');
    }
    return $query;
}

add_filter('pre_get_posts','SearchFilter');

Source: wprecipes.com →

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'); ?>">
  <div>
    <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" />
  </div>
</form>

Source: www.melandri.net →

Dynamically Search Categories and 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.’,';
}
$catlist.’5′;
?>
<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” />
</div><!–/search –>
</form>

Source: wpgarage.com →

Search a Specific 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
add_filter('pre_get_posts','SearchFilter');

Source: ashbluewebdesign.com →

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.'";
      </script>
    ';
  }
}

function hls_init_jquery() {
  wp_enqueue_script('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; }
  </style>
  <script type="text/javascript">
  jQuery.fn.extend({
    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>";
      }));
    }
  });
  jQuery(document).ready(function($){
    if(typeof(hls_query) != 'undefined'){
      $("#post-area").highlight(hls_query, 1, "hls");
    }
  });
  </script>

Source: weblogtoolscollection.com →

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;" ) );

Source: wpengineer.com →

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(); ?>

Source: wphacks.com →

Implement Google AJAX Search API

Implement Google AJAX Search APIImplement Google AJAX Search API →
Demo →
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

Create an Ajax-based Auto-completing Search Field for WordPressCreate 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.
Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn’t really optimized.

How To Add Google Custom Search To WordPress

How To Add Google Custom Search To WordPressGoogle Custom Search Engine →
In this tutorial you will be shown how to integrate Google’s Custom Search Engine into your blog, making it easier for your readers to find content and allow you to make some money with Adsense.
How To Add Google Custom Search To WordPress →

You might also like…

30 Grid-Based WordPress Themes →
40 More Stylish, Minimal and Clean Free WordPress Themes →
30 Brand New Quality WordPress Themes →
45+ Fresh WordPress Tutorials, Techniques and Hacks →
10 Blank/Naked WordPress Themes Perfect for Development →
25 Fresh, Clean and Unique WordPress Themes →
40 Awesome and Fresh WordPress Themes →
Essential WordPress Plugin Development Resources, Tutorials and Guides →
20+ Powerful WordPress Security Plugins and Some Tips and Tricks →
20+ Free and Stylish Typography WordPress Themes →

Author: (569 Posts)

Paul Andrew is the editor and founder of Speckyboy Design Magazine. You can follow Speckyboy on Twitter, on Facebook, on Digg or you can subscribe via RSS.

  • Pingback: 10 Useful WordPress Search Code Snippets | گالان هاست | Galan Host

  • http://www.stunningmesh.com Wijdan Rohail

    Whenever I found these kind of important information, I bookmark that site, so this one also added my Bookmarks.

  • http://gulalisweet.co.cc/ zoeldt

    very useful, thanks!

  • http://www.kiranvoleti.com kiran voleti

    Very useful code snippets.Thanks for sharing.

  • http://www.djavupixel.com djavupixel

    Very useful code snippets because some are really useful on some projects.

  • http://www.pixiegirldesigns.com Yaritsa

    This is great, was just looking for some additional search options. Thanks for posting!

  • http://wpgarage.com Miriam Schwab

    Very useful post! And I’m glad you shared our tip from WPGarage.com :)

  • http://www.dentalheroes.com Cory from Dental Heroes

    Very useful, thanks. I think these are especially useful since WordPress has a less-than-ideal search function “out-of-the-box”.

    As my site grows, the Google Custom Search option is looking better and better.

  • http://k-win.fr kevin

    Bookmarked as well, very usefull.

  • http://www.AlchemyUnited.com Mark @ Alchemy United

    Excellent! Thanks!!

    Does anyone know if the Search By Category can be applied to taxonomies as well?

  • http://www.jockjerseys.com/ Cory H

    These are all great and I hope to use one or more of them once I get a little further along w/ my website.

    For now though, I’m stuck on how to remove the “+” sign between the actual query itself when I display it on the search results page.

    Try searching for “lebron james” or another athelete… The search results show “lebron+james” in the Title tag and displayed on the page. Not very user friendly.

    Anyone know how to troubleshoot this? I’ve tried the regular forum, etc. but that didn’t get any resolution.

    • Anonymous

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

  • http://www.web-lovers.de Rolf Moczarski

    Thanks for sharing this great stuff !

  • http://www.hastishah.com Hastimal Shah

    Thanks for sharing
    its very useful code snippets..

  • Pingback: Resources and links – 24 September 2010

  • Pingback: Ressources pour concepteur de modèle pour Internet

  • Pingback: 10 Useful WordPress Search Code Snippets « Referência própria do wordpress

  • http://www.senseforweb.com webdesign in bangladesh

    Thank you for Exclude Posts or Pages from Search Results code. Really nice sharing.

  • Pierre

    Congratulations from France. Very useful post

  • http://www.sagive.co.il sagive

    wonderfull!! this is exactly what i was looking for
    thanks a bunch

  • Pingback: WordPress pretraga | WordPress škola

  • Pingback: Wordpress Custom Post Type Search | dBaines.com

  • Pingback: Useful Plugins and Resources for Improving User Interactivity with WordPress | Preukson

  • Pingback: 10 Useful Wordpress Search Code Snippets - Quid de l'internet : blog seo, php, css, dev, psd | Quid de l'internet : blog seo, php, css, dev, psd

  • Wow! eBook

    Very useful post. It help my site search better.

  • Pingback: Improve Wordpress Search | The Laudun Log

  • Anonymous

    The post is absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep ‘em coming… you all do such a great job at such Concepts… can’t tell you how much I, for one appreciate all you do!

  • Pingback: Five Iterations of Site Search » AI3:::Adaptive Information

  • Scott

    Here´s one way how to remove pages or categories from search ..
    http://tocs-i.com/blog/exclude-pages-or-include-specific-categories-in-wordpress-search/

  • 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!

  • http://www.gowebbaby.com/ WordPress Customization

    A perfect post,I totally agree with you.. wonderful analysis of the matter,as WordPress Designer i explore many things. well done and thanks for sharing your grate ideas and information.

  • http://wpeos.com/ Lvcatlerbuzz

     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 ;)