10 Useful WordPress Search Code Snippets

It is no secret that the standard search within WordPress is not the best. 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 WordPress search code snippets that will help improve the search accuracy for your readers.

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 →

(638 Posts)

Paul Andrew

Paul is the founder and editor of Speckyboy Design Magazine. He has many years experience within the web design industry and a passion for the latest web technologies and design trends. He lives in the small town of Inverness in the north of Scotland. Follow him on Twitter, Facebook or Google+.

Comments

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