Hacks and snippets to enhance WordPress search engine

by Jean. 8 Comments -

WordPress built-in search engine is often cited as one of the weak points of the popular blogging platform. In this article, I have compiled several code snippets to make WordPress search engine a lot better.

Redirect to first post if only one post is found

Let’s start with a handy snippet that will automatically redirect the reader to the post if only one post is found. Simply paste it in your functions.php file and you’re done.

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

Source: http://www.paulund.co.uk/redirect-search-results…

Display the number of results in WordPress search

When a search is done on your blog, WordPress does not return the number of results found. Though, this can be useful for the person who made the search.

In order to display the number of results, open your search.php file. In it, search for the following:

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

Now replace it with:

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

Source: http://www.problogdesign.com/wordpress/3-codes-for-a-far-better…

Enlight searched text in search results

Here is an easy way to make your search results more user-friendly: Enlight searched text.
To do so, open your search.php file and find the the_title() function. Replace it with:

echo $title;

Now, just before the line you just modified, add this code:

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

Save the search.php file and open style.css. Append the following line to it:

strong.search-excerpt { background: yellow; }

That’s all. Better, isn’t it?

Source: http://yoast.com/wordpress-search/

Limit posts per page on search

By default, WordPress outputs 10 posts per page on the search results page. If you need to change this number, just paste the following code in your functions.php file. Replace the number on line 3 by the desired number of posts to be displayed.

function limit_posts_per_search_page() {
	if ( is_search() )
		set_query_var('posts_per_archive_page', 20); 
}

add_filter('pre_get_posts', 'limit_posts_per_search_page');

Source: http://wordpress.org/support/topic/limit-post-per-search-page

Search within post type only

If you want to force the search engine to search only within a specific post type, here is the solution. Paste the code below into your functions.php file after you changed the post type name on line 4.

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: http://www.hongkiat.com/blog/wordpress-search-plugin-snippet/

Limit search to specific categories

Is it also possible to limit search to specific categories. To do so, just replace the categories IDs on line 3 and paste the following code on your search.php template:

<?php if( is_search() )  :
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("s=$s&paged=$paged&cat=1,2,3");
endif; ?>

Source: http://www.wprecipes.com/how-to-limit-search-to-specific-categories

Completely shut down WordPress search

Although search is a really useful feature on most websites, sometimes you simply don’t need it at all. Did you knew that you could completely shut down WordPress search? Just include the function below in 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: http://wpengineer.com/1042/disable-wordpress-search/

Make your search results unlimited

As I already stated before, the fact that WordPress displays 10 posts by default on the search results page can be annoying. If you’d like to display unlimited search results on the same page, here’s an easy way to do it.

In search.php, find the code below:

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

Once you found it, replace it by this:

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

That’s all. You’re done!
Source: http://wphacks.com/how-to-make-wordpress-search-results-unlimited/

Comments (8) - Leave yours

  1. Giovanni said:

    Very useful!

    I’m searching a way to search in taxonomies only and not in the posts content.

    For example: I search the word “fish” and the result shows only the post tagged with “fish”.

    Do you know if I can do it and how?

    Thanks,
    Giovanni

  2. Chris Kuffner said:

    Thanks for the post, it definitely came in handy.

    To search for more than one specific post type use an array:

    $query->set(‘post_type’, array(‘post’, ‘pages’, ‘feeds’));

  3. Alan Smith said:

    “Completely shut down WordPress search” , as a blogger we should not shut down the search because this feature allow users to find the content in an easy manner. I agree that above codes are useful but please suggest me that is there any add-ons which give me all so facilities?

  4. Saugrin Sonia said:

    Hi,

    I’m french and my english is bad. I’ve a question for Display ” the number of results in WordPress search “, why not use :

    the_search_query(); && $wp_query->found_posts;

  5. Ryan Hellyer said:

    Be careful with that. You could easily cripple your site if someone searched for something commonly found in your posts, like “a”, as it would cause your site to load up every post which has that letter in it. For example, on my own blog that would result in over 400 posts being displayed, which would likely bog the server down quite badly and take an awfully long time to load the page.

  6. Xps said:

    WordPress search results are sorted descending by date rather than relevancy. As your site expands, you’ll likely desire such functionality for your readers and opt for something like Google’s Custom Search.
    http://www.google.com/cse/

    Redirect to first post- You probably should inform the reader that only one result came up, and that’s why they’re redirected. Otherwise, they may think they missed out on reviewing the results because they don’t realize (or doubt) the query only had one result.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!