猿问

在每个后循环后重置计数器

我在自定义 post 类型循环中有一个 ACF 中继器,该循环带有一个计数器,每两个 col-md-6 围绕一行。当我有偶数个 col 时,这很有效,但当它不均匀时就不行了。当一篇文章的列数不均匀时,计数器会以某种方式记住下一篇文章,并且只在第一行显示一个列。


在这里,您将找到当前代码和正在发生的事情的小图片。不知何故,我需要在每次发布循环后重置计数器,但无法弄清楚。wp_reset_postdata 似乎不起作用。


<?php $args = array( 'post_type' => 'posttypename', 'posts_per_page' => '-1' ); $the_query = new WP_Query( $args ); ?>

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

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


<div>

    <div class="container">


        <div class="row">


            <div class="col-md-12">

                <h1><?php the_title(); ?></h1>

            </div>


        </div>


        <?php if( have_rows('row') ): ?>

            <div class="row">

            <?php while( have_rows('row') ): the_row(); $text = get_sub_field('text'); ?>


                <div class="col-md-6">      

                    <?php echo $text; ?>

                </div>


                <?php $counter++; if($counter % 2 === 0) :  echo '</div> <div class="row">'; endif; ?>

            <?php endwhile; ?>

            </div>

        <?php endif; ?>


    </div>

</div>


<?php endwhile; ?>

<?php wp_reset_postdata(); ?>

<?php endif; ?>

ibeautiful
浏览 114回答 1
1回答

呼唤远方

只是一个小小的改变。您需要确保在循环acf开始之前将您的计数器重置为 0。&nbsp; &nbsp; &nbsp; &nbsp; <?php $counter = 0; //Initialize your Counter here before the Loop Starts for each Post ?>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <?php if( have_rows('row') ): ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="row">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php while( have_rows('row') ): the_row(); $text = get_sub_field('text'); ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="col-md-6">&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php echo $text; ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php $counter++; if($counter % 2 === 0) :&nbsp; echo '</div> <div class="row">'; endif; ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?php endwhile; ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <?php endif; ?>
随时随地看视频慕课网APP
我要回答