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'm using WP from an external PHP script by including the wp-load.php file.

All functions and everything works as expected so far, except one thing: I can't get the $wp_query->found_posts to work after I fetch posts with get_posts() function.

Any hints what should I be using instead?

Thanks!

share|improve this question
add comment

1 Answer 1

The WordPress function get_posts() is making it's own instance of WP_Query that is not globally accessible:

function get_posts($args = null) {
    // ... cut ...
    $get_posts = new WP_Query;
    return $get_posts->query($r);
}

so you could instead try

 $results = get_posts($args);
 echo count($results);

to give you the array count of post objects returned by get_posts().

WP_Query() class usage example:

You could consider using the WP_Query() class directly.

Here is an example how you can use it:

<?php
// your input parameters:   
$args = array(
    'posts_per_page' => 10,
);

$my_query = new WP_Query( $args );?>

Found posts: <?php echo $my_query->found_posts;?>

<?php if ( $my_query->have_posts() ):?>
    <ul>
        <?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
            <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; ?>
    </ul>
<?php endif; ?>

<?php wp_reset_postdata();?>    

We use wp_reset_postdata() in the end, to restore the global $post object, since we change it via the_post() method.

Reference:

http://codex.wordpress.org/Function_Reference/wp_reset_postdata

http://codex.wordpress.org/Class_Reference/WP_Query

share|improve this answer
    
Thanks for your answer. However that won't really work - the get_posts() will return the number of items per page I determine. If there are 100 posts in total and I fetch 10, counting the results like this will still give me 10. Hope this makes sense. –  Ivanhoe123 May 13 '13 at 8:38
    
Dirty solution would be to run the query twice, with numberposts parameter set to -1 and count these results. But it's horrible from performance point of view and I doubt this is the correct solution. –  Ivanhoe123 May 13 '13 at 8:45
    
What about using WP_Query instead of get_posts? –  birgire May 14 '13 at 12:24
    
Will give it a try. Should I use again the $wp_query->found_posts to get the count of all results? –  Ivanhoe123 May 14 '13 at 19:12
    
you should use something else than $wp_query, for example $my_query = new WP_Query($args); and then $my_query->found_posts and remember to use wp_reset_postdata() in the end if you change the global $post object. –  birgire May 14 '13 at 20:38
show 1 more comment

Your Answer

 
discard

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

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