admin管理员组文章数量:1426804
I'm trying to get a count of the current posts inside of a loop. I'm using multiple loops on one page in my theme. So far I have:
$my_post_count = $wp_query->post_count;
But when I print $my_post_count, it returns the number all of the posts on my WP site. Could it have something to do with using multiple queries on one page? I tried using wp_reset_query after every loop to make sure I wasn't throwing things off that way. What am I doing wrong?
I'm trying to get a count of the current posts inside of a loop. I'm using multiple loops on one page in my theme. So far I have:
$my_post_count = $wp_query->post_count;
But when I print $my_post_count, it returns the number all of the posts on my WP site. Could it have something to do with using multiple queries on one page? I tried using wp_reset_query after every loop to make sure I wasn't throwing things off that way. What am I doing wrong?
Share Improve this question asked Oct 16, 2011 at 18:17 pwbredpwbred 5481 gold badge3 silver badges11 bronze badges4 Answers
Reset to default 38$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()
then WP_Query
object is not accessible and you should just count returned set:
$posts = get_posts();
$count = count($posts);
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;?>
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;
?>
Simple way to count total post including pagignation
<?php global $wp_query
echo $wp_query->found_posts; ?>
本文标签: wp queryGet post count of current loop when using multiple queries on one page
版权声明:本文标题:wp query - Get post count of current loop when using multiple queries on one page 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745478121a2660056.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论