Post Pic

How to: Display the number of results in WordPress search

WordPress users know it: Search is definitely one of WordPress weak point. Today, let’s see how to get the number of results the search returned, and display it (proudly!) on our blog.

Open your search template file, search.php. In it, search for the following:

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

Now replace this 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>

That's all, you're done!

Credits goes to ProBlogDesign for this awesome WordPress recipe!

By the way, I'm going to publish a big article of 10 awesome WordPress hacks on my other blog Cats Who Code tomorrow. Be sure to suscribe to our RSS feed so you're gonna miss it!

16 Responses

Mar 18 2009 18:32

Thanks for the link back Jean-Baptiste!

Mar 18 2009 19:07

echo $wp_query->found_posts;

That’s all for the search result.

Mar 20 2009 10:21

Thanks. There are some problems with the code box in IE6, in Mozilla works fine.

Mar 23 2009 05:51

Great, thank you for this easy fix!

Mar 26 2009 20:44

That’s a good start, but it needs code to address this sort of search result:

Search for “convoluted PHP” found 1 articles

Mar 29 2009 18:18

great idea. thanks for it

Jun 22 2009 21:12

Like frank already stated (2nd comment) this single line ‘echo $wp_query->found_posts;’ will give the number of posts returned for search, tags and archives…

Oct 26 2009 17:52

Great! Many thanks!

Dec 21 2009 00:14

I agree search is definitely one of Wordpress’s strong points. I never thought about adding the number of results to the search page, but since you have offered such a simple addition, I went ahead and added it. Hope my users find it useful.

Jan 24 2010 16:08

I don’t like it: you effectively relaunch the same sql search query again, instead of fetching the count from the current (already existing) resultset.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required