Useful WordPress Code Snippets to Improve Search

WordPress, the versatile CMS powering over one-fifth of the entire web has only a few weak points to talk about. Its built-in search is one such feature that limits its capabilities to a great extent.

The search is too vague to be of much use and leaves most users baffled. Would not it be wonderful if you had a tool or custom code to bolster up its search function so that your site visitors get a great experience every single time they visit your site and optimally use the search function of your site! Here are some useful WordPress code snippets to do that.

1. Exclude Pages or Posts

In case you want certain pages or posts to be excluded from the results page, you can copy and paste this code in the functions.php file. This code excludes categories with ids 0 and 1 from search results. Specify the appropriate categories to suit your needs.

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

2. If there is only one post, redirect to it by default

If there is only one post, you would want your visitors to be directed to it by default. Use the following code to achieve this purpose:

1
2
3
4
5
6
7
8
9
add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

3. Search Form with Drop Down having categories

It would be great if you could limit your search to a specific category. The following code will help in adding a drop down form with all the categories.

1
2
3
4
5
6
7
8
< 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>

4. Show the number of Results

While performing search on a WordPress blog, the number of results obtained is not shown on the search page. The following code:

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

in the search.php file needs to be replaced with this code:

1
2
3
4
5
6
7
8
9
10
<h2 class="pagetitle">Search Results 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(' — '); 
echo $count . ' '; _e('articles'); 
 
wp_reset_query(); ?></h2>

5. Specify a particular post type for searching

One can search specific post types using a simple code snippet that can be added to the functions.php file:

1
2
3
4
5
6
7
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

1
add_filter('pre_get_posts','SearchFilter');

6. Enlight searched text

Searched text can be enlightened using a simple code snippet. In the search.php file, replace the_title() function with echo $title;

Now, add this snippet just before the code you just added:

1
2
3
4
5
6
7
<?php
	$title 	= get_the_title();
	$keys= explode(" ",$s);
	$title 	= preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong class="search-excerpt">\0</strong>',
		$title);
?>

7. Use jQuery to highlight search terms

The following code snippet can be used for highlighting search terms to help users.

1
2
3
4
5
6
7
8
9
10
11
function hls_set_query() {
  $query  = attribute_escape(get_search_query());
 
  if(strlen($query) > 0){
    echo '
      <script type="text/javascript">
        var hls_query  = "'.$query.'";
      </script>
    ';
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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>

8. Limit the number of posts per page

By default, WordPress displays 10 posts per page. If you wish to change this number, you can add the following code to your functions.php file:

1
2
3
function limit_posts_per_search_page() {
	if ( is_search() )
		set_query_var('posts_per_archive_page', 20);

The number in line number three can be changed to any value suitable to you.

9. Make the WordPress search unlimited

WordPress happens to display up to 10 posts by default. You can make your WordPress search unlimited by replacing the following code in search.php by the snipped provided below.
Replace:

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

With this:

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

10. Completely shut down WordPress Search

It is even possible to completely shut down WordPress search. Copy this code into your functions.php file to achieve this purpose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;" ) );

Don’t miss out these all-time favourites

  1. The best hosting for a WordPress website. Tap our link to get the best price on the market with 82% off. If HostPapa didn’t impress you check out other alternatives.
  2. Website Installation service - to get your template up and running within just 6 hours without hassle. No minute is wasted and the work is going.
  3. ONE Membership - to download unlimited number of WordPress themes, plugins, ppt and other products within one license. Since bigger is always better.
  4. Ready-to-Use Website service is the ultimate solution that includes full template installation & configuration, content integration, implementation of must-have plugins, security features and Extended on-page SEO optimization. A team of developers will do all the work for you.
  5. Must-Have WordPress Plugins - to get the most essential plugins for your website in one bundle. All plugins will be installed, activated and checked for proper functioning. 
  6. Finest Stock Images for Websites - to create amazing visuals. You’ll get access to Depositphotos.com to choose 15 images with unlimited topic and size selection.
  7. SSL Certificate Creation service - to get the absolute trust of your website visitors. Comodo Certificate is the most reliable https protocol that ensures users data safety against cyber attacks. 
  8. Website speed optimization service - to increase UX of your site and get a better Google PageSpeed score.

Mini Belwal

Apps, snippets, plugins and other useful software - that is what I am in love with. Modern supportive technologies make website building much easier - so why not use them?

Get more to your email

Subscribe to our newsletter and access exclusive content and offers available only to MonsterPost subscribers.

From was successfully send!
Server error. Please, try again later.

Leave a Reply