如何为一行中的每个第二个div添加一个类

时间:2018-01-30 16:40:02

标签: php wordpress

我想连续每隔一个项添加一个类,请帮助,   提前致谢

添加一些虚拟内容以满足其标准

<?php $counter = 1 ?> 
     <div class="services-posts mt2 pull-right">
      <?php
       $args = array( 'post_type' => 'services');
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <?php $featured_img_url = get_the_post_thumbnail_url('full');  ?>
                <div class="col-sm-4 <?php if ($counter % 2 == 0) : ?> animation-fadeInUp <?php endif; ?> <?php if ($counter % 1 == 0) : ?> animation-fadeInLeft <?php endif; ?> <?php if ($counter % 3 == 0) : ?> animation-fadeInRight <?php endif; ?> "  >
                    <?php if (has_post_thumbnail( $post->ID ) ): ?>
                    <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
                    /*I need to add a class to the each second box-div2 div */
                     <div style="background-image: url('<?php echo $image[0]; ?>')"   class="box-div2">
                     <?php endif; ?>
                    <div class="c-div">
                        <a href="">
                            <h4><?php the_title(); ?></h4>
                            <span>
                                <?php the_content(); ?>
                            </span>
                    </a>
                        </div>
                    </div>
                </div>
                 <?php if ($counter % 3 == 0){echo '</div><div class="services-posts mt2 pull-right">';} ?> 
                  <?php $counter++ ; ?>
                <?php endwhile; ?> 

4 个答案:

答案 0 :(得分:1)

您是指每一个查询结果吗?如果是这样,这应该有效:

<?php $div2_class = $counter % 2 == 0 ? 'your-class' : ''; ?>
<div style="background-image: url('<?php echo $image[0]; ?>')" class="box-div2 <?php echo $div2_class; ?>">

答案 1 :(得分:1)

作为粗略的万物解决方案,您可以使用ternary运算符和modulo运算符:

<?php echo (($counter % 2 == 0) ? $theThingYouWantToEcho : null) ?>

括号内的代码表示:

  • 如果$counter / 2是整数(分割时没有余数)
  • 然后返回$theThingYouWantToEcho
  • else return null(nothing)

然后,echo语句将打印出该结果。

您可以将$theThingYouWantToEcho替换为您要添加的CSS类

<div class="<?php echo (($counter % 2 == 0) ? 'myClass' : null) ?>">...</div>

答案 2 :(得分:1)

使用这个,我创建了一个变量$ divclass,它将相应地添加该类。

替换:

/*I need to add a class to the each second box-div2 div */
<div style="background-image: url('<?php echo $image[0]; ?>')"   class="box-div2">

使用:

<?php 
    $divclass="";
    if ($counter%2==0) {
        $divclass="box-div2";
    }
?>
<div style="background-image: url('<?php echo $image[0]; ?>')"   class="<?php echo $divclass;?>">

答案 3 :(得分:1)

我不是你做这个的原因是什么,但如果是为了造型目的,CSS允许你选择偶数/奇数元素:

a:nth-child(odd) {
    background: green;
}

a:nth-child(even) {
    background: red;
}

使用公式(an + b)甚至可以使用其他周期,而不仅仅是奇数/偶数。

另一方面,如果出于编程原因,jQuery也有奇数/偶数选择器:

$("tr:odd").css("background-color", "green");
$("tr:even").css("background-color", "red"); 

所以通常你不需要类来分隔奇数/偶数元素。

相关问题