3

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!

1 Answer 1

10

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

6
  • 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. Commented 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. Commented May 13, 2013 at 8:45
  • What about using WP_Query instead of get_posts?
    – birgire
    Commented 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? Commented 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
    Commented May 14, 2013 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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