如何添加一个类到php循环中的每个第n个项目(wordpress) [英] How do I add a class to every nth item in a php loop (wordpress)

查看:191
本文介绍了如何添加一个类到php循环中的每个第n个项目(wordpress)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Wordpress循环如下:

I have a Wordpress loop as follows:

<?php $loop = new WP_Query( array( 'post_type' => 'portfolio' ) ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <div class="four columns">
        <?php the_content(); //along with other stuff in looped div ?>
    </div>
<?php endwhile ?>

如何为每个第4n-3个div

How can I add an 'alpha' class to every (4n-3)th div (div.four.columns) and an 'omega' class to every (4n)th item using php?

感谢(很多!),
Jamie

Thanks (a lot!), Jamie

推荐答案

为什么不添加一个计数器,并使用模数方法来了解每一列你当前回应什么元素。

Why not add a counter and use the modulus approach to get to know in every column what element you are currently echoing.

假设您有4列指定。

您从counter = 1开始

1%4 = 1在第一个元素中)

2%4 = 2(您在第二个元素中)

3%4 = 3(您在第三个元素中)

4%4 = 0(您在第四个元素中)

5%4 = 1(您位于第一个元素中)

6%4 = 2(您在第二个元素中)

Lets say you have 4 columns as specified.
You start with counter = 1
1 % 4 = 1 ( you are in the first element )
2 % 4 = 2 ( you are in the second element )
3 % 4 = 3 ( you are in the third element )
4 % 4 = 0 ( you are in the fourth element )
5 % 4 = 1 ( you are in the first element )
6 % 4 = 2 ( you are in the second element )

您只需使用If语句,类如下:

And you just use an If statement with the class as following

<?php $counter = 1 ?>
<?php $loop = new WP_Query( array( 'post_type' => 'portfolio' ) ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <div class="four columns <?php if ($counter % 4 == 1){echo 'alpha'}else if ($counter % 4 == 0){echo 'omega'} ?>">
        <?php the_content(); //along with other stuff in looped div ?>
    </div>
<?php $counter++ ; 
endwhile ?>

这篇关于如何添加一个类到php循环中的每个第n个项目(wordpress)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆