WordPress search count results

You want to create a search page in WordPress where you count the results and show them on your page, for example: Searching for “apple” gives 3 results.

For getting this search counting you need to add the following code in your search file where you want to show this “counting sentence”.

First we make these variables:

<?php
$allsearch = &new WP_Query("s=$s&showposts=-1");
$key = wp_specialchars($s, 1);
$count = $allsearch->post_count;
?>

Then we use $key for showing the search query and $count for how much results.

<p>Searching for "<?php echo $key;?>" gives <?php echo $count;?> results.</p>

Class “last” with counter

With this piece of code you can get posts with the get_posts function and if you have for example 3 divs next to each other and you want the third with a class=”last”, than you can use the following code:

<?php $post_counter = -2; ?>
<?php
$posts = get_posts('&cat=1&numberposts=5');
foreach( $posts as $post ) : ?>
<?php $post_counter++; ?>
<div class="classname <?php if( $post_counter == count( $posts )) { echo "last"; }?>">
</div>
<?php endforeach; ?>