计算两个循环内的总项数 - 循环内循环

时间:2013-11-27 10:41:03

标签: php wordpress loops counter

项目: 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>

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

1 个答案:

答案 0 :(得分:0)

对于计数你可以像这样使用

<?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');
?>
相关问题