How to limit the number of fetched items by a WP_Query

The ‘posts_per_page’ is not limiting the number of items WP_Query will fetch.
Which is OK, however I need to find a way how to break the WP_Query with some limit or break like attribute after 3 items are fetched. I have many items and to fetch 3 items it get all the 1000+ items in my database, which is slowing down the page in the end.

Any idea how to limit the query to get only 3 instead of all items from the db?

$args = array(
    'post_type' => array( 'books' ),
    'meta_query' => array(
        array(
            'key' => 'book_state',
            'value' => 'sold'
        )
    ),
    'posts_per_page' => 3,
);
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) : 

    $booksNumber  = $the_query->found_posts; // returns 1282 instead of 3

    ...

Related posts

2 comments

  1. found_posts returns the total number of posts matching the query parameters.

    post_count returns the total number of posts being displayed. I believe what you want to do is:

    $booksNumber  = $the_query->post_count;
    

    If that doesn’t work, I would try using get_posts instead of WP_Query:

    $postslist = get_posts($args);
    $booksNumber = count($postslist);
    
  2. It looks like you’re only using one meta query, so try using get_posts.

    Normally, I’d recommend WP_Query, but I can see how it can be confusing. If you run the following code you will see something more like what you’re expecting:

    $args = array(
        'post_type' => 'books',
        'meta_key' => 'book_state',
        'meta_value' => 'sold',
        'posts_per_page' => 3,
    );
    $posts = get_posts($args);
    echo count($posts);
    var_dump($posts);
    

Comments are closed.