Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have two different pieces of code and it's returning two different results.

$search_query = new WP_Query();
$search_posts = $search_query->query('s=computer'); 
echo count($search_posts);

vs.

$search_posts = get_posts('s=computer');
echo count($search_posts);

What is the reason for the different values?

(The value provided by the first one is correct. It's the same as the number of posts that I get when I do a regular search in WP. But the first piece of code won't work inside the plugin's php file, it would work only in a template.)

Thanks.

share|improve this question
add comment

1 Answer

The default arguments for get_posts() function include 'numberposts' => 5.

So if you're querying for a search term that returns more than five (5) results the second query will return a maximum value of 5 unless you pass 's=computer&numberposts=-1' as your query string.

The WP_Query object doesn't have a 'numberposts' default, although it is affected by the "Blog pages show at most" count in your settings panel. So if you want the total count using the query() function, you should override the defaults like this:

$search_query->query('s=computer&nopaging=true')
share|improve this answer
    
@goldenapples - Nice answer! –  MikeSchinkel Oct 9 '10 at 1:41
    
Thank you so much for the answer. It was driving me crazy and all along there was very simple explanation :-) –  Dan Oct 9 '10 at 14:27
    
@Dan - If @goldenapples answer solved your problem please remember to select the checkmark for this answer to give him or her the credit they deserve. –  MikeSchinkel Oct 10 '10 at 0:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.