2015-11-03 21:40
浏览 205


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(
            '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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duancheng6500 2015-11-03 21:55

    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);
    打赏 评论
  • douzhong6480 2015-11-03 21:53

    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);
    打赏 评论

相关推荐 更多相似问题