1

I have this code that counts the result found when a search is made. Here goes the code.

<?php /* Search Count */ 
    $allsearch = &new WP_Query("s=$s&showposts=-1"); 
    $key = wp_specialchars($s, 1); 
    $count = $allsearch->post_count; 
    $text  = '<span class="resultsFound">';
if ( $allsearch->found_posts <= 0 ) {
    $text .= sprintf(__( '( Nothing Found )' ), $count );
}

elseif ( $allsearch->found_posts <= 1 ) {
    $text .= sprintf(__( '( We found %d company )' ), $count );
} 

else {
    $text .= sprintf(__( '( We found %d companies )' ), $count );
}       
$text .= '</span>'; 
echo $text;
?>

The code above is the code for counting all the post found in search page. I want to apply this function to my category as well as tag page. Any solution?

1

Don't run a custom query to get the post count. This is already done by the main query. What you are doing is the same as eating the same piece of meat twice. :-)

As said, the main query already return the amount of posts found via the $found_posts property. You can access and display it anywhere on a page as follows

echo $wp_query->found_posts;

This will print the amount of posts that the main query found that mathes the URL request.

You can use the following on any page in your site, just change the text as needed

<?php 
    /* Search Count */ 
    $count = $wp_query->found_posts; 
    $text  = '<span class="resultsFound">';
if ( $count  <= 0 ) {
    $text .= sprintf(__( '( Nothing Found )' ), $count );
}

elseif ( $count <= 1 ) {
    $text .= sprintf(__( '( We found %d company )' ), $count );
} 

else {
    $text .= sprintf(__( '( We found %d companies )' ), $count );
}       
$text .= '</span>'; 
echo $text;
?>
7
  • Hi! Thanks for your answer! I tried your code. But, that is only showing number instead of "1 result found" or "2 results found". Would you please implement a code which works that way? Thanks! :) – Jornes Mar 25 '15 at 8:28
  • Please see my update. I have taken your code from your question and modified it. It will work anywhere. You can replace your code with mine. Just change the wording on your pages – Pieter Goosen Mar 25 '15 at 8:31
  • Thanks Peter! But, would it work on tag page as well? – Jornes Mar 25 '15 at 8:32
  • Yes, you can drop it in any page like your tag pages and category pages – Pieter Goosen Mar 25 '15 at 8:35
  • Just one note, in my code, please remove the $key part. Will update code now – Pieter Goosen Mar 25 '15 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.