Skip to content

10 Useful WordPress Search Code Snippets

setembro 25, 2010

Post Ctrl+C,Ctrl+V from

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.

1 function SearchFilter($query) {
2 if ($query->is_search) {
3 $query->set('cat','0,1');
4 }
5 return $query;
6 }
8 add_filter('pre_get_posts','SearchFilter');

Source: →

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:

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

Source: →

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.

01 <form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
02 <div id=”search”>
03 <input type=”text” value=”Search… ” onclick=”this.value=”;” name=”s” id=”s” />
04 <?php $categories = get_categories(‘child_of=1′);
05 $catlist = ”;
06 foreach ($categories as $cat) {
07 $catlist.= $cat->cat_ID.’,';
08 }
09 $catlist.’5′;
10 ?>
11 <input type=”hidden” name=”cat” value=”<?php echo $catlist”?>” />
12 <input name=”" type=”image” src=”<?php bloginfo(‘stylesheet_directory’); ?>/styles/<?php echo $style_path”; ?>/search.gif” value=”Go” class=”btn” />
13 </div><!–/search –>
14 </form>

Source: →

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.

01 function SearchFilter($query) {
02 if ($query->is_search) {
03 // Insert the specific post type you want to search
04 $query->set('post_type', 'feeds');
05 }
06 return $query;
07 }
09 // This filter will jump into the loop and arrange our results before they're returned
10 add_filter('pre_get_posts','SearchFilter');

Source: →

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:

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

And replace it with this code:

1 <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>'); echo $key; _e('</span>'); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>

Source: →

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:

01 function hls_set_query() {
02 $query = attribute_escape(get_search_query());
04 if(strlen($query) > 0){
05 echo '
06 <script type="text/javascript">
07 var hls_query  = "'.$query.'";
08 </script>
09 ';
10 }
11 }
13 function hls_init_jquery() {
14 wp_enqueue_script('jquery');
15 }
17 add_action('init', 'hls_init_jquery');
18 add_action('wp_print_scripts', 'hls_set_query');

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

01 <style type="text/css" media="screen">
02 .hls { background: #D3E18A; }
03 </style>
04 <script type="text/javascript">
05 jQuery.fn.extend({
06 highlight: function(search, insensitive, hls_class){
07 var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
08 return this.html(this.html().replace(regex, function(a, b, c){
09 return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "</strong>";
10 }));
11 }
12 });
13 jQuery(document).ready(function($){
14 if(typeof(hls_query) != 'undefined'){
15 $("#post-area").highlight(hls_query, 1, "hls");
16 }
17 });
18 </script>

Source: →

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.

01 function fb_filter_query( $query, $error = true ) {
03 if ( is_search() ) {
04 $query->is_search = false;
05 $query->query_vars[s] = false;
06 $query->query[s] = false;
08 // to error
09 if ( $error == true )
10 $query->is_404 = true;
11 }
12 }
14 add_action( 'parse_query', 'fb_filter_query' );
15 add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Source: →

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:

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

And then add this code:

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

Source: →

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 →

No comments yet

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do

Você está comentando utilizando sua conta Sair /  Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )


Conectando a %s

%d blogueiros gostam disto: