如何对循环显示的所有帖子求和

How to make a sum of all posts displayed in a loop

我想找出一种方法来打印循环显示的所有帖子的总和。例如:

<?php if (have_posts()) :

$total_count = 1;
while (have_posts()) : the_post(); 
echo $total_count;
endwhile;
endif;

?>

Returns: 1 1 1 1 1 1 1

因为我的循环中有 7 个帖子。但是,我想对所有这些 1 求和,以便得到 7 作为结果。

有什么想法吗?

尝试增加您的 total_count,而不是每次都打印它。 您将为每个 post 添加 1,然后打印总值。检查 php 赋值运算符 +=

<?php if (have_posts()) :

$total_count = 0;
while (have_posts()) : the_post(); 
$total_count += 1;
endwhile;
echo $total_count;
endif;

?>

另请记住,您的计数器应始终从 0 开始。