[英]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. “ posts_per_page”不限制WP_Query将获取的项目数。 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.
没关系,但是我需要找到一种方法,在获取3个项目后,如何以一定的限制或类似like的属性来破坏WP_Query。 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.
我有很多项目,要获取3个项目,它将获得数据库中所有1000多个项目,这最终使页面变慢。
Any idea how to limit the query to get only 3 instead of all items from the db? 任何想法如何将查询限制为仅从数据库中获取3个而不是所有项目?
$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
...
found_posts
returns the total number of posts matching the query parameters. found_posts
返回与查询参数匹配的帖子总数。
post_count
returns the total number of posts being displayed. post_count
返回正在显示的帖子总数。 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
: 如果那不起作用,我将尝试使用get_posts而不是
WP_Query
:
$postslist = get_posts($args);
$booksNumber = count($postslist);
It looks like you're only using one meta query, so try using get_posts . 看起来您只在使用一个元查询,因此请尝试使用get_posts 。
Normally, I'd recommend WP_Query, but I can see how it can be confusing. 通常,我建议使用WP_Query,但我可以看到它如何造成混淆。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.