Count posts returned by get_posts in external PHP script

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.

Read More

Any hints what should I be using instead?

Thanks!

Related posts

1 comment

  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

Comments are closed.