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?


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:

// 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() ):?>
        <?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
            <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; ?>
<?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.




  • 1
    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. May 13, 2013 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. May 13, 2013 at 8:45
  • What about using WP_Query instead of get_posts?
    – birgire
    May 14, 2013 at 12:24
  • 1
    Will give it a try. Should I use again the $wp_query->found_posts to get the count of all results? May 14, 2013 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, 2013 at 20:38

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.