php - 简单的php计数器

标签 php wordpress counter

我正在研究 wordpress query_posts。我想在索引页上显示 12 个帖子,连续 3 个项目。所以我想在每一行的第一项上都有一个“clear:both”css。请问我该怎么做?

<?php query_posts(array('showposts' => 9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?>
<div>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div> <!-- clear class on each 4th item -->
            <h2><?php the_title(); ?></h2>
            <?php the_content(); ?>
        </div>
    <?php endif; ?>
</div>
<?php wp_reset_query(); ?>

最佳答案

<?php query_posts(array('showposts' => 9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?>
<div>
    <?php $i = 0; $attr = " class='clear_float'"; ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div<?php if(($i++)%3 == 0) {echo $attr;} ?>> <!-- clear class on each 4th item -->
            <h2><?php the_title(); ?></h2>
            <?php the_content(); ?>
        </div>
    <?php endif; ?>
</div>
<?php wp_reset_query(); ?>

我添加了 2 行。

<?php $i = 0; $attr = " class='clear_float'"; ?>

<div<?php if(($i++)%3 == 0) {echo $attr;} ?>> <!-- clear class on each 4th item -->

=====更新=====

要添加第 3 个项目类,我建议将类添加到所有项目,以实现简单性和更好的控制

为此,在循环之前:

$i = 0;

div里面在循环中:

<div class="item-<?php echo (($i++) % 3) + 1 ?>">

因此,对于每一行,第一项的类 = item-1 ,第三项的类别 = item-3

关于php - 简单的php计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3762233/

相关文章:

java - 每秒更新一次 MySQL 数据库

php - 如果已选中,如何将复选框值插入数据库表?

php - 是否有可能在 php 中获取调用者上下文的魔法常量?

php - 如何用 php/html 偏移图像?

python - 如何查找字符串中单词的计数

python - pycrypto 错误....ImportError : cannot import name Counter

php - WooCommerce 按钮可清除购物车、添加一件商品并前往结帐

css - Wordpress 主题 - 如何设置菜单样式?

html - 允许在 wordpress 简码内容中使用 HTML 标签吗?

swift - 每次调用时使用 func 来替代任务 a 或 b