在一页上使用多个查询时获得当前循环的发布计数
4 个回答
- 投票数
-
- 2011-10-16
$wp_query
保存页面的主循环,不应用于创建多个循环.如果您正在使用新的
WP_Query
对象,则保存该对象的变量将具有相应的计数:$my_query = new WP_Query(); // stuff $count = $my_query->post_count;
如果您使用的是
get_posts()
,则WP_Query
对象是不可访问的,您应该只对返回的集合进行计数:$posts = get_posts(); $count = count($posts);
$wp_query
hold main loop of page and should not be used to create multiple loops.If you are using new
WP_Query
object then your variable that holds it will have according count:$my_query = new WP_Query(); // stuff $count = $my_query->post_count;
If you are using
get_posts()
thenWP_Query
object is not accessible and you should just count returned set:$posts = get_posts(); $count = count($posts);
-
注意:如果您在主循环中,则可以通过`global $ wp_query`访问`WP_Query`.Note: If you are in the main loop, you can access `WP_Query` through `global $wp_query`
- 0
- 2019-10-22
- mrmadhat
-
- 2011-10-16
我相信post_count是存储在全局变量中的,因此在自定义循环之前,应将其设置为
0
,因为您可以在循环之外使用它,但这取决于您构造结构的方式多个查询,也许您可以将它们添加到您的帖子中?例如,我在循环中使用的另一种方法是使用
current_post + 1
对帖子进行计数.<?php $my_query = new WP_Query();?> <?php if ($my_query->have_posts()) :while ($my_query->have_posts()) : $my_query->the_post(); $count_posts = $my_query->current_post + 1; //counts posts in loop endwhile;?>
I believe the post_count is stored in the global, so before the custom loop you should set it to
0
, since you can use it outside the loop, but this depends on how you are structuring your multiple query's, maybe you can add them to your post?There is another way that I use within the loop that counts posts using
current_post + 1
, for example.<?php $my_query = new WP_Query();?> <?php if ($my_query->have_posts()) :while ($my_query->have_posts()) : $my_query->the_post(); $count_posts = $my_query->current_post + 1; //counts posts in loop endwhile;?>
-
- 2019-05-21
使用WP_Query的替代解决方案是:
<?php $args = array( 'post_type' => 'post' ); $the_query = new WP_Query( $args ); $totalpost = $the_query->found_posts; ?>
An alternative solution using WP_Query would be:
<?php $args = array( 'post_type' => 'post' ); $the_query = new WP_Query( $args ); $totalpost = $the_query->found_posts; ?>
-
- 2019-05-08
一种简单的方法来统计包括版次在内的总帖子数
<?php global $wp_query echo $wp_query->found_posts; ?>
Simple way to count total post including pagignation
<?php global $wp_query echo $wp_query->found_posts; ?>
我正在尝试获取循环中当前帖子的数量.我在主题的一页上使用了多个循环.到目前为止,我有:
但是当我打印$my_post_count时,它返回WP网站上所有帖子的编号.可能与在一页上使用多个查询有关吗?我尝试在每个循环之后使用wp_reset_query,以确保我不会那样扔东西.我在做什么错了?