Expand Search Results In WordPress

The search function in WordPress is expandable by many WordPress Plugins. For every desire something. But in this post I like to introduce a little code snippet, which doesn’t give you any of these functionality but shows the user how many posts where found including their search query.

With this little but nice help, it is an additional value for the user, as I think.

How such a result looks like, displays the following screen shot. The code only shows the number of results and can be adjust as you like to of course.

Searchresult example

To show the number of found posts, I just use a query of WordPress, quasi an extra loop. I define this loop new, and set that all (-1) entries should be used. If the parameter showposts won’t delivered with -1, WordPress will use the value, which settings are used for the output in the frontend.
The function wp_specialchars is not only used to filter, so there cannot be a XSS-leak but still include the search keyword in the output. The code is simple and straightforwarded – experiment with it. I’m happy if you have improvements or a better use for this.

<h2>Search Result<br /><small>
<?php /* Search Count */
	$allsearch = &new WP_Query("s=$s&showposts=-1");
	$key = wp_specialchars($s, 1);
	$count = $allsearch->post_count;
	_e('Begriff: ');
	echo $key;
	_e(' — ');
	echo $count . ' ';
	_e('Artikel'); wp_reset_query(); ?></small></h2>

The code should be put in search.php of the active theme. If this file isn’t existing, then the search function normally is in index.php. But to construct a better search for the user, I would recommend to use an own template.

In loop with $wp_query->found_posts

The above example should clarify the function, but it shouldn’t be used to use several loops in the template. Below you see a simple example for the template search.php, to show the number of search results with only one loop in your template.

<?php get_header();?>

	<h2>Search Results<br /><small><?php echo $wp_query->found_posts; ?> Article</small></h2>

	<?php if (have_posts()) { while (have_posts()) : the_post(); ?>
		<div class="post" id="post-<?php the_ID(); ?>">

			<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h3>
			<?php the_excerpt(); ?>

		</div>
		
	<?php endwhile; } else { ?>
	
	<p><?php _e('Nothing found, what meets your criteria.', 'basis'); ?></p>
	
	<?php } ?>

<?php get_footer(); ?>

Comments are closed.

One comment

  1. lotech

    Awesome! thanks.