【问题标题】:Count total items within two loops - loop within loop计算两个循环内的总项目数 - 循环内循环
【发布时间】:2013-11-27 10:41:02
【问题描述】:

项目: WordPress 项目
查询: WP_Query()

对于单个查询,我正在处理两个循环 - 我称之为循环内循环。结构如下:

<?php
while( $my_query -> have_posts() ) :
$my_query -> the_post();

if( condition) { ?>
    <div class="grid-box">
        <div class="item">Item of this kind</div>
    </div> <!-- .grid-box -->
<?php
}

if( condition) {
    $someCounter = grab some counter here;
    for( $inner = 0; $inner < $someCounter; $inner ++ ) {
    ?>
        <div class="grid-box">
            <div class="item">Item of that** kind#<?php echo $inner; ?></div>
        </div> <!-- .grid-box -->
    <?php
    } //end for
}

endwhile;
?>

使用 CSS,查询对我来说做得很好,以漂亮的网格块显示项目。但是如果项目多于一行,则第二行中的项目与第一行发生冲突。所以我打算把它们放在行类中,比如:

<div class="row">
   <!-- every 6 items within a grid -->
   <div class="grid grid-first>Item of this kind</div>
   <div class="grid>Item of this kind</div>
   <div class="grid>Item of that** kind</div>
   <div class="grid>Item of that** kind</div>
   <div class="grid>Item of this kind</div>
   <div class="grid grid-last>Item of that** kind</div>
</div>
<div class="row">
   <div class="grid grid-first>Item of that** kind</div>
   <div class="grid>Item of that** kind</div>
   <div class="grid>Item of this kind</div>
</div>

现在我需要计算总项目数。我怎样才能做到这一点?我是否需要通过两个计数器,如果需要,那么如何将它们结合起来计算确切的计数,然后使用计数作为条件来加载带有.row 的 div?请注意,正如我正在处理的那样,$inner 计数器对我的动态代码很重要。但是我们可以使用计数作为我们的总计数。

【问题讨论】:

  • 在开始第一个while循环之前,初始化$intTotal=0;,在for循环中增加$intTotal++;并在endwhile后面输出print sprintf('%d total rows', $intTotal);

标签: php wordpress loops counter


【解决方案1】:

count 你可以这样使用

<?php wp_count_posts( $type, $perm ); ?> 

要获取发布的状态类型,您可以调用 wp_count_posts() 函数,然后访问“发布”属性。

<?php
$count_posts = wp_count_posts();

$published_posts = $count_posts->publish;
?>

统计页面状态类型的方式与帖子相同,并使用第一个参数。查找帖子状态的帖子数量与查找帖子的方法相同。

<?php
$count_pages = wp_count_posts('page');
?>

【讨论】:

  • 很抱歉,wp_count_posts() 不适合这里,因为它只会计算主循环的帖子,而不是内循环 (for loop) 的项目。
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 2012-12-22
  • 2014-06-18
  • 2019-02-13
  • 1970-01-01
相关资源
最近更新 更多