Wordpress循环计数器问题

时间:2018-01-10 12:50:55

标签: php wordpress loops

我有这段代码可以通过自定义的帖子类型客户端...

<div class="wrap" style="padding-top: 0 !important;">

    <?php
        $args = array( 
          'post_type' => 'short_courses',
          // 'orderby' => 'none',
          'course_type' => 'digital-marketing'
        );
        $the_query = new WP_Query( $args );
    ?>

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


        <div class="one-third course-item">
            <a href="<?php the_permalink(); ?>">

                <p><img src="<?php the_field('listing_thumbnail'); ?>"></p>
                <h4><?php the_title(); ?></h4> 
                <p style="color: #f08464;"><?php the_field('date_for_thumbnail_listing'); ?></p>  
                <p><?php the_field('price'); ?></p>
                <a href="<?php the_permalink(); ?>" class="sc-box-button" style="background-color: #f08464; margin-bottom: 40px;">MORE INFO</a>

            </a>
        </div>

    <?php $products_count = $the_query->current_post + 1; ?>
    <?php if ( $products_count % 4 == 0): ?>

    <?php endif; ?>


    <?php endwhile; wp_reset_postdata(); endif; ?>

</div>

所有工作都很好,但位于底部:

<?php $products_count = $the_query->current_post + 1; ?>
<?php if ( $products_count % 4 == 0): ?>

我试图让物品在4件物品之后流到下一行...目前它正在3件物品之后进行...

道歉,如果它很简单我就错过了!

***** UPDATE FIXED ******

抱歉 - 我用CSS实现了这个效果,道歉但是我只是将CSS元素更改为:

@media (min-width: 576px) {
  .card-columns {
    column-count: 4; }
}

3 个答案:

答案 0 :(得分:2)

有两种方法: -

1.添加计数器befor循环,然后递增并检查( standered + best way

$products_count = 0;
<?php if ( have_posts() ) :
  //rest code as it is
<?php $products_count++; ?>
<?php if ( $products_count % 4 == 0): ?> //rest code as it is

2.或从<?php $products_count = $the_query->current_post; ?>

中删除+1

答案 1 :(得分:1)

我建议在此之前这样做:

$products_count = 0;

这是为了计算:

$products_count++;
if ( $products_count % 4 == 0): ...

答案 2 :(得分:1)

<?php $products_count = $the_query->current_post; ?>

仅从上述代码中删除+1。